Swift 2 学习笔记 6.数组
2018-11-18 本文已影响0人
Maserati丶
课程来自慕课网liuyubobobo老师
数组:有序的数据集合
- 数组的初始化
var numbers: [Int] = [0,1,2,3,4,5]
var vowels: [String] = ["A","E","I","O","U"]
var emptyArray1: [Int] = []
var emptyArray2: Array<Int> = []
var emptyArray3 = [Int]()
var emptyArray4 = Array<Int>()
var allZero = [Int](repeating: 0, count: 5)
- 数组的基本用法 --> Swift4
var numbers: [Int] = [0,1,2,3,4,5]
var vowels: [String] = ["A","E","I","O","U"]
var emptyArray: [Int] = []
numbers.count // 5
vowels.isEmpty // false
numbers[2] // 3
numbers.first // 1
emptyArray.first // nil
numbers.min() // 1
vowels.max() // "U"
numbers[2..<4] // [3,4]
vowels.contains("A") // true
vowels.firstIndex(of: "E") // 1
for (index, vowel) in vowels.enumerated() {
print("\(index):\(vowel)")
}
- 数组的更多用法 --> Swift4
var numbers: [Int] = [1,2,3,4,5]
numbers.append(6) // [1,2,3,4,5,6]
numbers += [7] // [1,2,3,4,5,6,7]
numbers.insert(0, at: 0) // [0,1,2,3,4,5,6,7]
numbers.removeLast() // [0,1,2,3,4,5,6]
numbers.removeFirst() // [1,2,3,4,5,6]
numbers.remove(at: 2) // [1,2,4,5,6]
numbers.removeSubrange(1...2) // [1,5,6]
numbers[0] = 0 // [0,5,6]
numbers[0...1] = [0] // [0,6]
numbers.removeAll() // []
- 二维数组
var board = [ [0,1], [0,1,2], [0,1,2,3] ]
board[0] // [0,1]
board[0][0] // [0]
board.count // 3
board[0].count // 2
board.append([0]) // [ [0,1], [0,1,2], [0,1,2,3], [0] ]
board[0].append(2) // [ [0,1,2], [0,1,2], [0,1,2,3], [0] ]
board += [ [0] ] // [ [0,1,2], [0,1,2], [0,1,2,3], [0], [0] ]