[swift-users] Cleaner way than if let initialization?
Erica Sadun
erica at ericasadun.com
Thu Aug 4 16:24:39 CDT 2016
And Greg from Omni Group has an even better solution for you. Since DateFormatter inherits from Formatter, you can use its `string(for:)` which accepts optionals:
let dobString3 = serverDateFormatter.string(for:dob) ?? ""
-- E
> On Aug 4, 2016, at 3:17 PM, Erica Sadun via swift-users <swift-users at swift.org> wrote:
>
>>
>> On Aug 4, 2016, at 1:41 PM, Tim Vermeulen via swift-users <swift-users at swift.org <mailto: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 <mailto:swift-users at swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org <mailto:swift-users at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-users <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/ff68cd17/attachment.html>
More information about the swift-users
mailing list