[Idea] Allowing definition of custom behaviors for `as` casting


(Yaman JAIOUCH) #1

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


(Tony Allevato) #2

What benefit would this provide that writing them as initializers already
doesn't? Writing the first two lines this way seems much clearer from a
call-site point of view:

let user1 = User(json: ["firstname": "Yaman", "lastname": "JAIOUCH"])
let user2 = User(string: "Yaman JAIOUCH")

That aside, placing the "as" methods on the destination type makes it look
to me like you're allowing casts *from* User *to* AnyObject/String and not
the other way around.

···

On Tue, Jun 21, 2016 at 8:27 AM Yaman JAIOUCH via swift-evolution < swift-evolution@swift.org> wrote:

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
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution