跳到主要内容

Swift Standard Library

Collections

Arrays

// Array operations
var numbers = [1, 2, 3, 4, 5]
numbers.append(6)
numbers.insert(0, at: 0)

// Higher-order functions
let doubled = numbers.map { $0 * 2 }
let evenNumbers = numbers.filter { $0 % 2 == 0 }
let sum = numbers.reduce(0, +)

Dictionaries

// Dictionary operations
var capitals = ["France": "Paris", "Japan": "Tokyo"]
capitals["Italy"] = "Rome"

// Dictionary methods
for (country, capital) in capitals.sorted(by: { $0.key < $1.key }) {
print("\(country): \(capital)")
}

String Processing

String Operations

// String manipulation
let greeting = "Hello, World!"
let substring = greeting.prefix(5)
let reversed = String(greeting.reversed())

// String interpolation
let name = "Swift"
let message = "Welcome to \(name) programming!"

Character Sets

let vowels = CharacterSet(charactersIn: "aeiou")
let text = "Hello"
let containsVowels = text.unicodeScalars.contains { vowels.contains($0) }

Numeric Types

Number Protocols

// Numeric protocol conformance
func double<T: Numeric>(_ value: T) -> T {
return value * 2
}

let intResult = double(5) // 10
let doubleResult = double(3.14) // 6.28

Mathematical Operations

// Math functions
let angle = Double.pi / 4
let sinValue = sin(angle)
let roundedValue = round(3.14159)

Optional Types

Optional Handling

// Optional chaining
struct Person {
var address: Address?
}

struct Address {
var street: String
var city: String
}

let person = Person()
let city = person.address?.city ?? "Unknown"

Optional Collections

// Optional array operations
let numbers: [Int]? = [1, 2, 3]
let firstNumber = numbers?.first
let mapped = numbers?.map { $0 * 2 }

Result Types

Error Handling

enum ParseError: Error {
case invalidFormat
case outOfRange
}

func parse(_ input: String) -> Result<Int, ParseError> {
guard let number = Int(input) else {
return .failure(.invalidFormat)
}
guard (0...100).contains(number) else {
return .failure(.outOfRange)
}
return .success(number)
}

Sequences and Iterators

Custom Sequences

struct Fibonacci: Sequence {
func makeIterator() -> FibonacciIterator {
return FibonacciIterator()
}
}

struct FibonacciIterator: IteratorProtocol {
var current = 0
var next = 1

mutating func next() -> Int? {
let result = current
(current, next) = (next, current + next)
return result
}
}

// Usage
let fibonacci = Fibonacci()
let first10 = Array(fibonacci.prefix(10)) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Next Steps

  1. Learn about iOS and macOS Development
  2. Explore SwiftUI and UIKit
  3. Study Performance Optimization