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
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to