<div dir="ltr">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:<div><br></div><div><span style="color:rgb(33,33,33);font-family:"helvetica neue",helvetica,arial,sans-serif">let user1 = User(json: ["firstname": "Yaman", "lastname": "JAIOUCH"])</span><br style="color:rgb(33,33,33);font-family:"helvetica neue",helvetica,arial,sans-serif"><span style="color:rgb(33,33,33);font-family:"helvetica neue",helvetica,arial,sans-serif">let user2 = User(string: "Yaman JAIOUCH")</span><br style="color:rgb(33,33,33);font-family:"helvetica neue",helvetica,arial,sans-serif"><div><br></div><div>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.</div></div></div><br><div class="gmail_quote"><div dir="ltr">On Tue, Jun 21, 2016 at 8:27 AM Yaman JAIOUCH via swift-evolution <<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">What you think about having the possibility to define custom behavior while casting with `as` keyword ?<br>
It could be quite handy to use while keeping a good level of readability.<br>
<br>
Something like this :<br>
<br>
struct User {<br>
let firstname: String<br>
let lastname: String<br>
<br>
as(json: AnyObject) -> User? {<br>
guard let json = json as? [String: AnyObject], let firstname = json["firstname"] as? String, let lastname = json["lastname"] else {<br>
return nil<br>
}<br>
<br>
return User(firstname: firstname, lastname: lastname)<br>
}<br>
<br>
as(string: String) -> User? {<br>
let components = string.componentsSeparatedByString(" ")<br>
guard components.count == 2 else { return nil }<br>
<br>
return User(firstname: components[0], lastname: components[1])<br>
}<br>
}<br>
<br>
let user1 = ["firstname": "Yaman", "lastname": "JAIOUCH"] as? User // returns valid user<br>
let user2 = "Yaman JAIOUCH" as? User // returns valid user<br>
let user3 = 24 as? User // returns nil<br>
let user4 = NSDate() as! User // crash as usual<br>
_______________________________________________<br>
swift-evolution mailing list<br>
<a href="mailto:swift-evolution@swift.org" target="_blank">swift-evolution@swift.org</a><br>
<a href="https://lists.swift.org/mailman/listinfo/swift-evolution" rel="noreferrer" target="_blank">https://lists.swift.org/mailman/listinfo/swift-evolution</a><br>
</blockquote></div>