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

Erica Sadun erica at ericasadun.com
Thu Aug 4 16:17:22 CDT 2016


> On Aug 4, 2016, at 1:41 PM, Tim Vermeulen via swift-users <swift-users at swift.org> wrote:
> 
> You want `flatMap`:
> 
> let dobString = dob.flatMap(serverDateFormatter.stringFromDate)
> 
> Or if you want `dobString` to be non-optional:
> 
> let dobString = dob.flatMap(serverDateFormatter.stringFromDate) ?? “"

You can just use map here too, right?

let dobString2: String = dob.map(serverDateFormatter.string) ?? ""

I was a little surprised that this didn't need the rest of the selector signature but that's because parameter stripping and type matching, isn't it?

> 
>> Currently I do stuff like this:
>> 
>> letdobString:String
>> ifletdob = dob {
>> dobString =serverDateFormatter.stringFromDate(dob)
>> }
>> else{
>> dobString =""
>> }
>> 
>> Is there a better, more idiomatic, way to do this sort of thing?
>> 
>> 
>> 
>> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


More information about the swift-users mailing list