Last active
December 16, 2015 07:28
-
-
Save externvoid/8ca689954f67f3968d17 to your computer and use it in GitHub Desktop.
as?, as!はどちらもdowncast、??はnilに備える演算子、?がfalseに備える演算子であるのと似ている
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
| 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