03--swift之集合

1.數組數組

var a: Array<Int> = Array<Int>()app

a.append(1)oop

var a1:[Int] = [1,2,3]spa

var a2 = [2,3]orm

2.如何建立空數組排序

var a3 = Array<Int>()ci

var a4 = [Int]()rem

a4.append(1)it

print(a4)io

a4 = []//置空

3.設置默認值數組

var ints = [Int](count: 5, repeatedValue: 100)

for e in ints{

print(e)

}

4.數組相加

var a1 = [1,2,3]

var a2 = [4,5,6]

var a3 = a1+a2

for e in a3{

print(e)

}

print("---------")

a3+=[7,8,9]

for e in a3{

print(e)

}

5.直接賦值

var a1 = [1,2,3]

var a2 = [4,5,6]

var a3: Array<String> = ["tom","kite"]

var a4 = ["ab","bc"]

6.判斷數組是否爲空

var a = [1,2,3]

print(a.count)

print(a.isEmpty)

print("--------")

a.removeAll(keepCapacity: false)

print(a.count)

print(a.isEmpty)

7.訪問數組

var a = [1,2,3]

for var i = 0;i<a.count;++i{

print(a[i])

}

8.修改數組

func loop(a: [Int]){

print("-------")

for e in a{

print(e)

}

}

var a = [1,2,3]

a.append(4)

loop(a)

a.insert(5, atIndex: 4)

loop(a)

a.removeLast()

loop(a)

9.排序

func loop(a: [Int]){

print("-------")

for e in a{

print(e)

}

}

var a = [5,4,6,3,1,2]

a = a.sort({ (a1, a2) -> Bool in

return a1>a2

})

//a.sortInPlace { (a1, a2) -> Bool in

//    return a1>a2

//}

loop(a)

10. 遍歷

var a = [1,2,3,4]

for (index,value) in EnumerateSequence(a){

print("\(index):\(value)")

}

11.sets

 語法

var s = Set<Int>()

s.insert(1)

s.insert(1)

s.insert(2)

 空集合

func loop(s: Set<Int>){

for e in s{

print(e)

}


}

var s = Set<Int>()

s.insert(1)

s.insert(2)

loop(s)

s = []

print(s.count)

print(s.isEmpty)

用數組字面量建立集合

func loop(s: Set<Int>){

for e in s{

print(e)

}


}


var s: Set = [1,2,3]//必須註明set


loop(s)

  添加和刪除,遍歷,判斷根array差很少

  var s: Set = [1,2,3]

  print(s.contains(3))

 集合的操做

  func loop(s: Set<Int>){

  for e in s{

  print(e)

  }

  

  }

  var s1: Set = [1,3,5,7]

  var s2: Set = [1,4,6,7]

  var r: Set = s1.intersect(s2)//交集

  loop(r)

  print("--------")

  r = s1.union(s2)//並集

  loop(r)

  print("--------")

  

  r = s1.exclusiveOr(s2)//除去交集以外的

  loop(r)

  print("---------")

  r = s1.subtract(s2)//一個集合除去與另外一個的交集剩下的

  loop(r)

  12.字典

   語法

  var dic: Dictionary<Int,String>

  dic = Dictionary<Int,String>()//init

  dic[1] = "tom"

  var dic2: [Int : String] = [1:"tom",2:"kite"]

  建立空字典

  var dic = Dictionary<Int,String>()

  var dic1 = [Int:String]()

  數組字面量建立字典

  var dic = [1:"tom",2:"kite",3:"rose"]

  字典訪問修改

  var dic = [1:"tom",2:"kite"]

  print(dic[1]!)

  print(dic.count)

  print(dic.isEmpty)

  dic[3] = "joe"//添加

  dic.updateValue("big kite", forKey: 2)//更新

  print(dic.count)

  dic[2] = nil//置空

  遍歷字典

  var dic = [1:"tom",2:"kite"]

  for (key,value) in dic{

  print("\(key):\(value)")

  }

  for key in dic.keys{

  print(key)

  }

  for value in dic.values{

  print(value)

  }

相關文章
相關標籤/搜索