跳转至

Swift 笔记 | 标准库常用函数

Swift Standard Library Values and Collections

  • Numbers and Basic Values
  • Strings and Text
  • Collections
  • Time

Bool

Swift
1
2
var isPresenting = Bool.random()
isPresenting.toogle()

Int

init

Double

Swift
1
2
let x = Int(21.5) // x == 21
let y = Int(-21.5) // y == -21

radix

Swift
1
2
let a = Int("100", radix: 2)! // a == 4
let b = Int("FF", radix: 16)! // b == 255

random

Swift
1
let a = Int.random(in: 1..<100)

constants

Swift
1
2
3
Int.zero // 0
Int.max // 9223372036854775807
Int.min // -9223372036854775808

calculation

quotient

Swift
1
2
let x = 1_000_000
let (q, r) = x.quotientAndRemainder(dividingBy: 933) // q == 1071, r == 757
Swift
1
2
15.isMultiple(of: 3) // true
15.isMultiple(of: 4) // false

abs

Swift
1
2
abs(2) // 2
abs(-2) // 2

binary representation

Swift
1
2
3
4
5
Int.bitWidth // 64
0b11010.bitWidth // 64
0b11010.nonzeroBitCount // 3
0b11010.leadingZeroBitCount // 59
0b11010.trailingZeroBitCount // 1

Double

init

random

Swift
1
Double.random(in: 10.0 ..< 20.0)

constants

Swift
1
2
3
Double.pi
Double.infinity
Double.nan

calculation

Swift
1
4.0.squareRoot() // 2
Swift
1
2
3
4
5
6
7
8
1.5.rounded(.down) // 1.0
1.5.rounded(.up) // 2.0
1.5.rounded(.towardZero) // 1.0
1.5.rounded(.awayFromZero) // 2.0
1.5.rounded(.toNearestOrAwayFromZero) // 2.0

var floar = 1.5
float.round(...)

Range

Swift
1
2
3
4
5
6
let underFive = 0.0 ..< 5.0 
underFive.contains(3.14) // true
underFive.lowerBound // 0.0
underFive.upperBound // 5.0
let empty = 0.0 ..< 0.0
empty.isEmpty // true
Swift
1
2
3
4
// 将当前的范围限制在新给定的范围中
func clamped(to limits: Range<Bound>) -> Range<Bound>
// 两个Range范围是否重叠
func overlaps(_ other: Range<Bound>) -> Bool

Global Numeric Functions

Swift
1
2
3
min(...)
max(...)
abs(...)

String

init

Swift
1
2
3
4
init(_ c: Character)
init(_ substring: Substring)
init(repeating repeatedValue: String, count: Int)
init(repeating repeatedValue: Character, count: Int)
Swift
1
init<Subject>(describing instance: Subject)
Swift
1
2
3
init(decoding path: FilePath)
init(contentsOf url: URL) throws
init(contentsOfFile path: String) throws
Swift
1
2
3
String(5, radix: 2) // "101"
String(255, radix: 16) // "ff"
String(255, radix: 16, uppercase: true) // "FF"

properties

Swift
1
2
3
4
let str = "Hello"
str.count // 5
let empty = ""
empty.isEmpty // true
Swift
1
2
func lowercased() -> String
func uppercased() -> String
Swift
1
2
3
func hasPrefix(_ prefix: String) -> Bool
func hasSuffix(_ suffix: String) -> Bool
func contains<T>(_ other: T) -> Bool where T : StringProtocol // Equivalent to self.range(of: other) != nil
Swift
1
2
3
4
5
func prefix(_ maxLength: Int) -> Self.SubSequence
func prefix(through position: Self.Index) -> Self.SubSequence
func prefix(upTo end: Self.Index) -> Self.SubSequence
func suffix(_ maxLength: Int) -> Self.SubSequence
func suffix(from start: Self.Index) -> Self.SubSequence

index

Swift
1
2
3
let str = "Hello, world!"
str.startIndex
str.endIndex

Character

Swift
1
2
3
let name = "Marie Curie"
let firstSpace = name.firstIndex(of: " ") ?? name.endIndex
let firstName = name[..<firstSpace] // "Marie"

String

Swift
1
2
let range = "Hello".range(of: "ll")! // 返回第一个查找到的词
print("Hello"[range]) // ll 

add

Swift
1
2
3
4
5
6
7
8
var a = "Hello"
a.append(contentsOf: ", world!")
print(a)
var b = "Hello"
b.insert(contentsOf: ", world!", at: b.endIndex)
print(b)
var c = "Hello"
print(c + ", world!")

replace

Swift
1
2
3
4
var str = "Hello, world!"
let helloRange = str.range(of: "Hello")!
str.replaceSubrange(helloRange, with: "Welcome")
print(str) // Welcome, world!
Swift
1
2
3
4
var str = "Hello, world!"
let worldRange = str.range(of: ", world")!
str.removeSubrange(worldRange)
print(str) // Hello!
Swift
1
2
let str = "Hello, world!"
print(str.replacingOccurrences(of: "Hello", with: "Welcome")) // Welcome, world!

split and join

Swift
1
2
3
4
5
6
func split(
    separator: Self.Element,
    maxSplits: Int = Int.max,
    omittingEmptySubsequences: Bool = true
) -> [Self.SubSequence]
func joined(separator: String = "") -> String

Array

init

Swift
1
2
3
var emptyDoubles: [Double] = []
var emptyFloats: Array<Float> = Array()
var digitCounts = Array(repeating: 0, count: 10)

properties

Swift
1
2
3
// When you need to check whether your collection is empty, use the isEmpty property instead of checking that the count property is equal to zero.
var isEmpty: Bool { get }
var count: Int { get }
Swift
1
2
3
func contains(_ element: Self.Element) -> Bool
func contains(where predicate: (Self.Element) throws -> Bool) rethrows -> Bool
func allSatisfy(_ predicate: (Self.Element) throws -> Bool) rethrows -> Bool

index

Swift
1
2
3
4
5
6
7
var startIndex: Int { get } // always 0
var endIndex: Int { get } // use `..<`

func firstIndex(of element: Self.Element) -> Self.Index?
func lastIndex(of element: Self.Element) -> Self.Index?

func index(of element: Self.Element) -> Self.Index?

element

Swift
1
2
3
4
5
6
7
var first: Self.Element? { get }
func first(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?

var last: Self.Element? { get }
func last(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?

func randomElement() -> Self.Element?

append and remove

Swift
1
2
3
mutating func append(_ newElement: Element)
mutating func append<S>(contentsOf newElements: S)
mutating func insert<C>(contentsOf newElements: C, at i: Self.Index)
Swift
1
2
3
4
5
6
@discardableResult mutating func removeFirst() -> Self.Element
@discardableResult mutating func removeLast() -> Self.Element
mutating func popLast() -> Self.Element?

mutating func removeSubrange(_ bounds: Range<Self.Index>)
mutating func removeAll(where shouldBeRemoved: (Self.Element) throws -> Bool) rethrows

replace

Swift
1
mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C)

sort

Swift
1
2
3
4
5
6
mutating func sort(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows
func sorted(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> [Self.Element]
mutating func reverse()
func reversed() -> ReversedCollection<Self>
mutating func shuffle()
func shuffled() -> [Self.Element]

split and join

Swift
1
2
3
4
5
6
7
func split(
    separator: Self.Element,
    maxSplits: Int = Int.max,
    omittingEmptySubsequences: Bool = true
) -> [Self.SubSequence]
func joined() -> FlattenSequence<Self>
func joined<Separator>(separator: Separator) -> JoinedSequence<Self> where Separator : Sequence, Separator.Element == Self.Element.Element

forEach and map

Swift
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// forEach效果和map一样的 只不过不返回;与for-in相比 for-in可以使用break 因为本质上是循环 而forEach可以理解为一个函数调用 与循环无关所以不能使用break
func forEach(_ body: (Self.Element) throws -> Void) rethrows
func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
// `s.flatMap(transform)` is equivalent to `Array(s.map(transform).joined())`.
func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence 
// 将元素中为nil的项去除
func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
func reduce<Result>(
    _ initialResult: Result,
    _ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result

example

Swift
1
2
3
let possibleNumbers = ["1", "2", "three", "///4///", "5"]
let mapped: [Int?] = possibleNumbers.map { str in Int(str) } // [1, 2, nil, nil, 5]
let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) } // [1, 2, 5]

for-in

Swift
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func enumerated() -> EnumeratedSequence<Self>

func stride<T>(
    from start: T,
    to end: T, // to 不包含end; through 包含end
    by stride: T.Stride
) -> StrideTo<T> where T : Strideable

func sequence<T>(
    first: T,
    next: @escaping (T) -> T?
) -> UnfoldFirstSequence<T>

func zip<Sequence1, Sequence2>(
    _ sequence1: Sequence1,
    _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> where Sequence1 : Sequence, Sequence2 : Sequence

example

Swift
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
for (n, c) in "Swift".enumerated() {
    print("\(n): '\(c)'")
}

for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) {
    let degrees = Int(radians * 180 / .pi)
    print("Degrees: \(degrees), radians: \(radians)") // 0, 90, 180, 270
}

for value in sequence(first: 1, next: { $0 * 2 }) {
    // value is 1, then 2, then 4, then 8, etc.
    print(value) // last print 1048576
    if value == 1024 * 1024 { break }
}

let words = ["one", "two", "three", "four"]
let numbers = 1...4
for (word, number) in zip(words, numbers) {
    print("\(word): \(number)")
}

Dictionary

properties

Swift
1
2
dict.keys
dict.values

for-in

Swift
1
for (key, value) in dict { ... }

Set

properties

Swift
1
2
3
4
5
6
7
func contains(_ member: Element) -> Bool

func isSubset(of other: Set<Element>) -> Bool
func isStrictSubset(of other: Set<Element>) -> Bool
func isSuperset(of other: Set<Element>) -> Bool
func isStrictSuperset(of other: Set<Element>) -> Bool
func isDisjoint(with other: Set<Element>) -> Bool
Swift
1
func randomElement() -> Self.Element?

insert and remove

Swift
1
2
@discardableResult mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element)
@discardableResult mutating func remove(_ member: Element) -> Element?

operation

return new set

Swift
1
2
3
4
func union<S>(_ other: S) -> Set<Element>
func intersection<S>(_ other: S) -> Set<Element>
func symmetricDifference<S>(_ other: S) -> Set<Element>
func subtracting<S>(_ other: S) -> Set<Element>

modify original set

Swift
1
2
3
4
mutating func formUnion<S>(_ other: S)
mutating func formIntersection<S>(_ other: S)
mutating func formSymmetricDifference<S>(_ other: S)
mutating func subtract<S>(_ other: S)