Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Array Cheat Sheet

Swift Array Cheat Sheet

初始化数组:

let arr = Array<Int>()
let arr1 = [Int]()
let arr2: [Int] = []
let arr3 = [1,2,3]
let arr4 = Array<Int>(repeating: 1, count: 3)
let arr5 = [Int](repeating: 1, count: 3)

检查数组

let arr = [1,2,3]

arr.count // 3
arr.isEmpty // false
arr.capacity // 3

访问元素

let arr = [1,2,3]

arr[0] // 1
arr.first // Optional(1)
arr.last // Optional(3)

arr[..<0] // []
arr[...0] // [1]
arr[0...] // [1,2,3]
arr[..<arr.endIndex] [1,2,3]

添加元素

var arr = [1,2,3]

arr.append(4) // [1,2,3,4]
arr.append(contentsOf: [5]) [1,2,3,4,5]

arr.insert(6, at: 5) // [1,2,3,4,5,6]
arr.insert([7], at 6) // [1,2,3,4,5,6,7]

arr.replaceSubrange(0..<3, [8]) // [8,4,5,6,7]

删除元素

var arr = [1,2,3,4,5,6,7,8,9,10]

arr.remove(at: 0) //[2,3,4,5,6,7,8,9,10]

arr.removeFirst() // [3,4,5,6,7,8,9,10]
arr.removeFirst(2) // [5,6,7,8,9,10]

arr.removeLast() // [5,6,7,8,9]
arr.removeLast(2) // [5,6,7]

arr.removeSubrange(1..<2) // [5,7]

arr.popLast() // [5]

查找元素

var arr = [1,2,3]

arr.contains(3) // true
arr.contains { $0 > 3 } // false

arr.index(of: 3) // 2
arr.index { $0 > 1 } // 1
arr.first { $0 > 1 } // 2

arr.min() // 1
arr.min { $0 > $1 } // 3

arr.max() // 3
arr.max { $0 < $1 } // 1

选择元素

var arr = [1,2,3]

// return ArraySlice
arr.prefix(2) // [1,2]
arr.prefix(through: 2) // [1,2,3]
arr.prefix(upTo: 2) // [1,2]
arr.prefix { $0 > 2 } // [1,2]

arr.suffix(2) // [2,3]
arr.suffix(from: 2) // [2,3]

排除元素

var arr = [1,2,3,4,5,6,7,8,9]

// return ArraySlice 
arr.dropFirst() // [2,3,4,5,6,7,8,9]
arr.dropFirst(2) // [4,5,6,7,8,9]

arr.dropLast() // [4,5,6,7,8]
arr.dropLast(2) // [4,5,6]

arr.drop { $0 < 5 } // [5,6]

遍历数组

for el in arr {
    print(el)
}

for i in 0..<arr.count {
    print(arr[i])
}

arr.forEach { el in
    print(el)
}

for (i, el) in arr.enumerated() {
    print("\(i) \(el)")
}

var iterator = arr.makeIterator()
while let el = iterator.next() {
    print(el)
}

for i in arr.indices {
    print(arr[i])
}

转换数组

var arr = ["1", "2", "three", "///4///", "5"]

// [1,2,nil,nil,5]
arr.map { str in Int(str) }

// [1,2,5]
arr.compactMap { str in Int(str) }

var arr1 = [2,3,4]
var sum = arr1.reduce(0) { result, next in
    return result + next
} //  9

var arr2 = arr1.reduce(into: [1]) { result, next in
    result += [next]
} // [1,2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.