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

Zhao Xin owenzx at gmail.com
Thu Aug 4 21:48:14 CDT 2016


Thank you. I think this is the best I saw today.

Zhaoxin

On Fri, Aug 5, 2016 at 5:24 AM, Erica Sadun via swift-users <
swift-users at swift.org> wrote:

> 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> 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
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
>
> _______________________________________________
> 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/20160805/0cabbe02/attachment.html>


More information about the swift-users mailing list