Skip to content

Instantly share code, notes, and snippets.

@externvoid
Last active December 16, 2015 07:28
Show Gist options
  • Select an option

  • Save externvoid/8ca689954f67f3968d17 to your computer and use it in GitHub Desktop.

Select an option

Save externvoid/8ca689954f67f3968d17 to your computer and use it in GitHub Desktop.
as?, as!はどちらもdowncast、??はnilに備える演算子、?がfalseに備える演算子であるのと似ている
var a: Any? = nil
a = 2
//a = 2.0
let b = a as? Int //可能ならOptionalへ、失敗ならnil
let c = a as! Int?
//let d = a as Int? compile error!!
let d = a as? Int?
//let e = a! // forced unwrap
print(b)
print(c)
print(d)
//
print(a.dynamicType)
print(b.dynamicType)
print(c.dynamicType)
//Optional(2)
//Optional(2)
//Optional(Optional(2))
//Optional<protocol<>>
//Optional<Int>
//Optional<Int>
var p: Any? = nil
p = 4
let q = p as? Int ?? 0
print(q)
print(q.dynamicType)
p = nil
let r = p as? Int ?? 0
print(r)
print(r.dynamicType)
p = 8
let s = p as? Int
print(s)
// 4
// Int
// 0
// Int
// Optional(8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment