Created
February 16, 2015 20:52
-
-
Save Gurpartap/a6b425d17571a4877c46 to your computer and use it in GitHub Desktop.
"select" non-nil elements.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "select" non-nil elements. | |
var data: Array<String> = ["0", "a"] | |
var wrappedIntsWithOptionals = data.map { $0.toInt() } as Array<Int?> | |
println("wrappedIntsWithOptionals: \(wrappedIntsWithOptionals)") | |
// wrappedIntsWithOptionals: [Optional(0), nil] | |
// ## This works | |
let wrappedInts = wrappedIntsWithOptionals.filter { $0 != nil } as Array<Int?> | |
println("wrappedInts: \(wrappedInts)") | |
// wrappedInts: [Optional(0)] | |
let mappedToUnwrapped = wrappedInts.map { $0! } as Array<Int> | |
println("mappedToUnwrapped: \(mappedToUnwrapped)") | |
// mappedToUnwrapped: [0] | |
// ## This does not | |
let unwrappedInts = wrappedIntsWithOptionals.filter { $0 != nil } as Array<Int> | |
// fatal error: can't unsafeBitCast between types of different sizes | |
println("unwrappedInts: \(unwrappedInts)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment