[swift-evolution] [Idea] Allowing definition of custom behaviors for `as` casting
Yaman JAIOUCH
yjaiouch at gmail.com
Mon Jun 20 15:03:20 CDT 2016
What you think about having the possibility to define custom behavior while casting with `as` keyword ?
It could be quite handy to use while keeping a good level of readability.
Something like this :
struct User {
let firstname: String
let lastname: String
as(json: AnyObject) -> User? {
guard let json = json as? [String: AnyObject], let firstname = json["firstname"] as? String, let lastname = json["lastname"] else {
return nil
}
return User(firstname: firstname, lastname: lastname)
}
as(string: String) -> User? {
let components = string.componentsSeparatedByString(" ")
guard components.count == 2 else { return nil }
return User(firstname: components[0], lastname: components[1])
}
}
let user1 = ["firstname": "Yaman", "lastname": "JAIOUCH"] as? User // returns valid user
let user2 = "Yaman JAIOUCH" as? User // returns valid user
let user3 = 24 as? User // returns nil
let user4 = NSDate() as! User // crash as usual
More information about the swift-evolution
mailing list