[swift-evolution] [Discussion]: Deprecate !-Unwrapping of Optionals

Charles Srstka cocoadev at charlessoft.com
Mon Feb 29 02:59:13 CST 2016

> On Feb 29, 2016, at 2:33 AM, Haravikk via swift-evolution <swift-evolution at swift.org> wrote:
> There are some cases where it’s still very useful even in pure Swift code. For example, say I have an array of optional values, and want to trip nils, then perform a transform on the result, I would do something like:
> 	let theResult = myArrayOfOptions.filter({ $0 != nil }).map({ doSomethingTo($0!) })

Not that I disagree that force-unwrapping is sometimes necessary (especially when working with Cocoa idioms that pretty much require it, such as NSDocument and anything involving NIB outlets), but for this particular example, you can just use flatMap to do this:

let theResult = myArrayOfOptions.flatMap { $0 }.map { doSomethingTo($0) }

You could even combine the two into one flatMap with a nil test in it, although it ends up looking pretty ugly (but should perform better).


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160229/a37b387d/attachment.html>

More information about the swift-evolution mailing list