Skip to content

Instantly share code, notes, and snippets.

@externvoid
Created January 7, 2016 08:02
Show Gist options
  • Select an option

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

Select an option

Save externvoid/b25d9b8399f29ceadf86 to your computer and use it in GitHub Desktop.
nilを返すかもしれないメソッドから値を受け取ってnon-optionalへ変換
nilを返すかもしれないメソッドから値を受け取る。
例:objectForKeyはAnyObject?を返す!!
[String: Int]?を[String: Int]へキャストする。
import Foundation
var obj: [String: Int]? = ["hp": 0]
print(obj)
var obj3: [String: Int] = obj! as [String: Int] ?? [String: Int]()
obj3["hp"] = 3
print(obj3)
print(obj3.dynamicType)
var obj4 = obj! as? Int
print(obj4.dynamicType)
// objの中身をunwrapせずに変更したい!!
//obj.map{ print($0.dynamicType) } // error: 'print' is unavailable:
// Please wrap your tuple argument in parentheses: 'print((...))'
// $0 = tuple, bug???
// obj.map{ $0["hp"] = 2 } // error: type of expression is ambiguous
// without more context ビックリ
// nilが返るかもしれないメソッドの取り扱い
//let obj6 = NSUserDefaults.standardUserDefaults().objectForKey("user data")
var obj6: AnyObject? = nil
print(obj6)
var obj5 = obj6 as? [String: Int] ?? [String: Int]()
//var obj5: [String: Int] = obj! as [String: Int] ?? [String: Int]()
obj5["hp"] = 3
print(obj5) // ["hp": 3]
print(obj5.dynamicType) // Dictionary<String, Int>
var obj7: [String: Int]! = obj6 as? [String: Int]
if obj7 == nil {
obj7 = ["hp": 3]
}
print(obj7.dynamicType) // Dictionary<String, Int>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment