Skip to content

Instantly share code, notes, and snippets.

@Gurpartap
Created February 16, 2015 20:52
Show Gist options
  • Save Gurpartap/a6b425d17571a4877c46 to your computer and use it in GitHub Desktop.
Save Gurpartap/a6b425d17571a4877c46 to your computer and use it in GitHub Desktop.
"select" non-nil elements.
// "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