Swift入门笔记
简单值
swift
复制代码
// 声明变量
var myVariable = 42
myVariable = 50
swift
复制代码
// 声明常量
let myConstant = 42
swift
复制代码
// 声明类型
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
swift
复制代码
// 显式类型转换
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
swift
复制代码
// 字符串中转换
let apples = 3
let appleSummary = "I have \(apples) apples"
swift
复制代码
// 多行内容
let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being wscaped.
I still have \(apples) pieces of fruit.
"""
swift
复制代码
// 创建数组
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
swift
复制代码
// 创建字典
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
swift
复制代码
// 数组添加元素
shoppingList.append("blueberries")
swift
复制代码
// 使用初始化器语法来创建一个空的数组
let emptyArray = [String]()
swift
复制代码
// 使用初始化器语法来创建一个空的字典
let emptyDictionary = [String: Float]()
swift
复制代码
// 如果类型信息能被推断(变量设置新的值或者传参数给函数)
shoppingList = []
occupations = [:]
控制流
swift
复制代码
// 控制流,if语句当中,条件必须是布尔表达式,不再隐式地与零做计算
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
swift
复制代码
// 等于符号赋值或者 return 后使用 if 或者 switch
let scoreDecoration =
if teamScore > 10 {
"🎉"
} else {
""
}
swift
复制代码
// ?把某个值标记为可选的
var optionalString: String? = "Hello"
swift
复制代码
// if-let操作那些可能会丢失的值,
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
swift
复制代码
// ??提供默认值
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
swift
复制代码
// Switch 选择语句支持任意类型的数据和各种类型的比较操作,不再限制于整型和测试相等
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
swift
复制代码
// for-in遍历字典
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (_, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
swift
复制代码
// while
var n = 2
while n < 100 {
n = n * 2
}
var m = 2
repeat {
m = m * 2
} while m < 100
swift
复制代码
// ..创造序列区间
var total = 0
for i in 0..<4 {
total += i
}
函数和闭包
swift
复制代码
// func声明函数
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)"
}
var s = greet(person: "Bob", day: "Tuesday")
swift
复制代码
// 默认使用形参作为实参,可以在形参前自定义实参名或者使用_避免使用实参
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)"
}
s = greet("John", on: "Wednesday")
swift
复制代码
// 使用元祖来创建复合值
func calculateStatics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
swift
复制代码
// 函数接受多个参数存放在数组中
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
var i = sumOf()
i = sumOf(numbers: 42, 597, 12)
swift
复制代码
// 内嵌函数可以访问外部函数里的变量
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
i = returnFifteen()
swift
复制代码
// 函数是一等类型,函数可以把函数作为值来返回
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
i = increment(7)
swift
复制代码
// 函数可以做参数
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
var b = hasAnyMatches(list: numbers, condition: lessThanTen)
swift
复制代码
// 闭包中用in分割实际参数和返回类型
var a = numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
swift
复制代码
// 闭包类型已知,可以去掉参数类型和返回类型
let mappedNumbers = numbers.map({ number in 3 * number})
print(mappedNumbers)
swift
复制代码
// 通过数字调用参数,当闭包时最后一个参数时,可以直接跟在圆括号后边。如果闭包是唯一参数,可以去掉圆括号。
let sortedNumbers = numbers.sorted { $0 > $1 }
对象和类
swift
复制代码
// 创建类
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
swift
复制代码
// 创建实例,访问实例的属性和方法
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
swift
复制代码
// 初始化器
class NameShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
swift
复制代码
// 子类重写父类的实现
class Square: NameShape {
var sideLength: Double
init(sideLength: Double, name: String){
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
var d = test.area()
s = test.simpleDescription()
swift
复制代码
// 计算属性
class EquilateralTriangle: NameShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String){
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
swift
复制代码
// 在设置一个新值前后执行代码
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
swift
复制代码
// 如果?前面的值是nil,那?后的所有内容都会被忽略并且整个表达式的值都是nil。否则,可选项的值将被展开,然后?后边的代码根据展开的值执行
let optionalSquare: Square? = Square(sideLength: 2.5, name:"optional square")
let sideLength = optionalSquare?.sideLength
枚举和结构体
swift
复制代码
// 枚举,默认从零开始给原始值赋值后边递增,可以通过制定特定的值来改变
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
swift
复制代码
// 使用init?(rawValue)初始化器从原始值创建枚举实例
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
print(threeDescription)
}
swift
复制代码
// 枚举成员的值是实际的值
enum Suit {
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades"
case .hearts:
return "hearts"
case .diamonds:
return "diamonds"
case .clubs:
return "clubs"
}
}
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
swift
复制代码
// case与值关联,值在初始化实例的时候确定,这样它们就可以在每个实例中不同了
enum ServerResponse {
case result(String, String)
case failure(String)
}
let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")
switch success {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset)")
case let .failure(message):
print("Failure... \(message)")
}
swift
复制代码
// 结构体在传递的时候拷贝其自身,而类会传递引用
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
并发
swift
复制代码
// async标记异步执行的函数
func fetchUserID(from server: String) async -> Int {
if server == "primary"{
return 97
}
return 501
}
swift
复制代码
// await标记对异步函数的调用
func fetchUsername(from server: String) async -> String {
let userID = await fetchUserID(from: server)
if userID == 501 {
return "John Appleseed"
}
return "Guest"
}
swift
复制代码
// async let可让它与其他异步函数并行执行,当要用返回值时,再使用await
func connectUser(to server: String) async {
async let userID = fetchUserID(from: server)
async let username = fetchUsername(from: server)
let greeting = await "Hello \(username), user ID \(userID)"
print(greeting)
}
swift
复制代码
// 在同步代码中调用异步函数,不用等它返回
Task {
await connectUser(to: "primary")
}
swift
复制代码
// 使用任务组来构造并发代码
let userIDs = await withTaskGroup(of: Int.self) { group in
for server in ["primary", "secondary", "development"] {
group.addTask {
return await fetchUserID(from: server)
}
}
var results: [Int] = []
for await result in group {
results.append(result)
}
return results
}
print(userIDs)
swift
复制代码
// 执行者确保不同异步函数可以在同一时间安全地与同一个执行者的实例进行交互
actor ServerConnection {
var server: String = "primary"
private var activeUsers: [Int] = []
func connect() async -> Int {
let userID = await fetchUserID(from: server)
activeUsers.append(userID)
return userID
}
}
swift
复制代码
// 调用执行者的方法或属性时,要用await标记代码以表明它可能需要等待其他正在访问的代码结束
let server = ServerConnection()
let userID = await server.connect()
协议和扩展
swift
复制代码
// protocol声明协议
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
swift
复制代码
// 类、枚举以及结构体都兼容协议,mutating关键字来声明使方法可以修改结构体,类中不需要这样声明
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anothorProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var aa = SimpleClass()
aa.adjust()
let aDescription = aa.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var bb = SimpleStructure()
bb.adjust()
let bDescription = bb.simpleDescription
swift
复制代码
// 使用extension来给现存的类型增加功能
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
swift
复制代码
// 当操作类型是协议类型的值的时候,协议外定义的方法是不可用的
let protocolValue: ExampleProtocol = aa
print(protocolValue.simpleDescription)
// print(protocolValue.anothorProperty)
错误处理
swift
复制代码
// 用任何遵循Error协议的类型来表示错误
enum PrinterError: Error {
case outOfPaper
case noToner
case onFire
}
swift
复制代码
// 使用throw来抛出错误并且用throws标记一个可以抛出错误的函数。如果在函数里抛出一个错误,函数会立即返回并且调用函数的代码处理错误
func send(job: Int, toPrinter printerName: String) throws -> String {
if printerName == "Never Has Toner" {
throw PrinterError.noToner
}
return "Job sent"
}
swift
复制代码
// 用do-catch处理错误。在do代码里,用try来在能抛出错误的函数前标记。在catch代码块,如果不给定其他名字,错误会自动赋予名字error。
do {
let printResponse = try send(job: 1040, toPrinter: "Bi Sheng")
print(printResponse)
} catch {
print(error)
}
swift
复制代码
// 提供多个catch代码块来处理特定的错误,用法和switch里的case一样
do {
let printResponse = try send(job: 1440, toPrinter:"Gutenberg")
print(printResponse)
} catch PrinterError.onFire {
print("I'll just put this over here, with the rest of the fire")
} catch let printerError as PrinterError {
print("Printer error: \(printerError).")
} catch {
print(error)
}
swift
复制代码
// 使用try?来转换结果为可选项。如果函数抛出了错误,那么错误被忽略并且结果为nil。否则,结果是一个包含了函数返回值的可选项
let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")
swift
复制代码
// 使用defer来写函数返回后也会被执行的代码,无论是否错误被抛出。甚至可以在没有任何错误处理的时候使用defer,来简化需要在多处地方返回的函数。
var fridgeIsOpen = false
let fridgeContent = ["milk", "eggs", "leftovers"]
func fridgeContains(_ food: String) -> Bool {
fridgeIsOpen = true
defer {
fridgeIsOpen = false
}
print(fridgeIsOpen)
let result = fridgeContent.contains(food)
return result
}
b = fridgeContains("banana")
print(fridgeIsOpen)
泛型
swift
复制代码
// 创建一个泛型方法或者类型
func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
var aes = makeArray(repeating: "knock", numberOfTimes:4)
print(aes)
swift
复制代码
// 可以从函数、方法、类、枚举、结构体创建泛型
enum OptionalValue<Wrapped> {
case none
case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)
swift
复制代码
// 类型名称后紧接where来明确一系列需求
func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
b = anyCommonElements([1, 2, 3], [3])
print(b)