Swift,字典

kimingw發表於2017-09-13

1、建立(Dictionary)字典(無序的可重複)

(1)指定型別

var a:Dictionary<String,String>=["a":"b"]

(2)簡單版指定型別

var b:[String:String]=["a":"w"]

(3)字面量建立(常用)

var b=["a":"w"]

2、新增、修改、刪除

(1)新增

var a=["a":"a"]
a["b"]="b"  //["a": "a", "b": "b"]

(2)修改

var a=["a":"a"]
a["a"]="b"  //["a": "b"]

(3)刪除

var a=["a":"a"]
a["a"]=nil
print(a.isEmpty)  //true

3、迴圈

(1)for迴圈鍵值對

var a=["a":"b"]
for (key,value) in a{
  print(key,value)  //a b
}

(2)for迴圈鍵

var a=["a":"b"]
for key in a.keys{
  print(key)  //a
}

(3)for迴圈值

var a=["a":"b"]
for value in a.values{
  print(value)  //b
}

4、分離成陣列

(1)分離鍵

var a=["a":"b"]
var b=[String](a.keys)  //["a"]

(2)分離值

var a=["a":"b"]
var b=[String](a.values)  //["b"]

  

  

相關文章