[swift-users] Cleaner way than if let initialization?

Erica Sadun erica at ericasadun.com
Thu Aug 4 15:51:15 CDT 2016


> On Aug 4, 2016, at 11:32 AM, Daniel Tartaglia via swift-users <swift-users at swift.org> wrote:
> 
> 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?

So if I understand this correctly `dob` is an optional date, and `dobString` is a non-optional String. Right? 

If that's what you're dealing with, then you  basically to do a double conditional: dob is optional, and stringFromDate returns optional, right? I'd do it like this:

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

But if serverDateFormatter is actually a NSDateFormatter instance, which does not return optionals, then you'd want to go with:

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

-- E
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160804/379f69a8/attachment.html>


More information about the swift-users mailing list