Idiomatic Swift: conditional unwrapping initialization

Datetime:2016-08-23 04:15:05         Topic: Swift          Share        Original >>
Here to See The Original Article!!!

Over on Swift-Users, Dan T asks:

Currently I do stuff like this:

let dobString: String
if let dob = dob {
    dobString = serverDateFormatter.stringFromDate(dob)
else {
    dobString = ""

Is there a better, more idiomatic, way to do this sort of thing?

I’m going to assume that serverDateFormatter is an instance of NSDateFormatter . If so, what Dan’s going for might be better expressed like this :

let dobString: String = {
    guard let dob = dob else { return "" }
    return serverDateFormatter.string(from: dob)

I think it’s a lot cleaner, and it only mentions dobString once. (If he’s not using NSDateFormatter and needs a second level of unwrapping, the guard let statement just needs a second clause that performs a conditional binding on the results of stringFromDate .)

Got a better solution? Toss it into the comments, tweet it, or hop onto the Swift-Users email list.


Put your ads here, just $200 per month.