该备忘单提供了使用 Swift 的示例,涵盖 Swift 基础知识、控制流、类型、结构/类、运算符、函数方法等。
入门 变量 1 2 3 4 5 6 7 8 9 10 var score = 0 let pi = 3.14 var greeting = "Hello" var numberOfToys = 8 var isMorning = true var numberOfToys: Int = 8 numberOfToys += 1 print (numberOfToys)
类型注释 1 2 3 4 var greeting: String = "Hello" var numberOfToys: Int = 8 var isMorning: Bool = true var price: Double = 8.99
算术运算符
1 2 3 4 5 6 var x = 0 x = 4 + 2 x = 4 - 2 x = 4 * 2 x = 4 / 2 x = 4 % 2
复合赋值运算符 1 2 3 4 var numberOfDogs = 100 numberOfDogs += 1 print ("有 \(numberOfDogs) 个斑点狗!" )
+=
添加和分配总和
-=
减去并分配差值
*=
乘并赋值
/=
除并分配商
%=
除并分配余数
字符串插值 1 2 3 var apples = 6 print ("I have \(apples) apples!" )
多行字符串 1 2 3 4 let myLongString = """ Swift? 这是我最喜欢的语言! """
代码注释
组成一个元组 1 2 3 4 let player = ("Maya" , 5 , 150 )print (player) print ("\(player.0 ) : level \(player.1 ) , \(player.2 ) pts" )
分解元组 1 2 3 4 let player = (name: "Maya" , level: 5 )let (currentName, curLevel) = playerprint ("\(currentName) : level \(curLevel) " )
特殊注释语法 (MARK)
MARK
可用于在栏中显示评论
特殊注释语法 (TODO)
TODO
用于显示需要完成的事情的提醒
特殊注释语法 (FIXME)
FIXME
用于显示需要修复的内容的提醒
变量 变量声明 变量用 var
声明:
1 2 3 var greeting = "你好" var numberOfToys = 8 var isMorning = true
为了清楚起见,变量声明可以包含类型注释:
1 2 3 var greeting: String = "你好" var numberOfToys: Int = 8 var isMorning: Bool = true
变量是可变的。 它们的值可以改变:
1 2 3 var numberOfToys: Int = 8 numberOfToys += 1 print (numberOfToys)
常数 常量用 let
声明:
1 2 3 let greeting = "Hello" let numberOfToys = 8 let isMorning = true
为清楚起见,常量声明可以包含类型注释:
1 2 3 let greeting: String = "Hello" let numberOfToys: Int = 8 let isMorning: Bool = true
常量是不可变的。它们的值不能改变:
1 2 3 let numberOfToys: Int = 8 numberOfToys += 1
计算变量(get 和 set) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import Foundationlet df = DateFormatter ()df.dateFormat = "d MMMM yyyy" var birth = df.date(from: "5 June 1999" )! var age: Int { Calendar .current .dateComponents([.year], from: birth, to: Date ()).year! } print (age) birth = df.date(from: "5 June 2002" )! print (age)
在下面的示例中,distanceInFeet 有一个 getter
和一个 setter
。 因为有 setter
,所以 getter
需要关键字 get
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 var distanceInMeters: Float = 100 var distanceInFeet: Float { get { distanceInMeters * 3.28 } set (newDistance) { distanceInMeters = newDistance / 3.28 } } print (distanceInMeters) print (distanceInFeet) distanceInFeet = 250 print (distanceInMeters) print (distanceInFeet) distanceInMeters = 800 print (distanceInMeters) print (distanceInFeet)
willSet 1 2 3 4 5 6 7 var distance = 5 { willSet { print ("距离将被设置" ) } } distance = 10
可以在 willSet
中访问新值:
1 2 3 4 5 6 7 var distance = 5 { willSet (newDistance) { print ("距离将被设置 \(newDistance) " ) } } distance = 10
willSet
可用于在设置变量值之前执行一些代码
didSet 1 2 3 4 5 6 7 8 var distance = 5 { didSet { print ("距离设置为 \(distance) " ) print ("它的旧值是: \(oldValue) " ) } } distance = 10
willSet 和 didSet 1 2 3 4 5 6 7 8 9 10 var distance = 5 { willSet (newDistance) { print ("距离将设置为 \(newDistance) " ) } didSet { print ("距离设置为 \(distance) " ) print ("它的旧值是: \(oldValue) " ) } } distance = 10
条件和逻辑 if 语句 1 2 3 4 5 6 7 8 9 10 11 var halloween = true if halloween { print ("不给糖就捣蛋!" ) } if 5 > 3 { print ("5 大于 3" ) } else { print ("5 不超过 3" ) }
else 语句 1 2 3 4 5 6 7 8 var turbulence = false if turbulence { print ("请坐好。" ) } else { print ("你可以自由地四处走动。" ) }
else if 语句 1 2 3 4 5 6 7 8 9 10 11 var weather = "rainy" if weather == "sunny" { print ("拿点防晒霜" ) } else if weather == "rainy" { print ("拿一把雨伞" ) } else if weather == "snowing" { print ("穿上你的雪地靴" ) } else { print ("无效天气" ) }
比较运算符 1 2 3 4 5 6 5 > 1 6 < 10 2 >= 3 3 <= 5 "A" == "a" "B" != "b"
<
小于
>
大于
<=
小于或等于
>=
大于或等于
==
等于
!=
不等于
三元条件运算符 1 2 3 4 5 var driverLicense = true driverLicense ? print ("驾驶座" ) : print ("乘客座位" )
switch 语句 1 2 3 4 5 6 7 8 9 10 11 12 13 var secondaryColor = "green" switch secondaryColor { case "orange" : print ("红色和黄色的混合" ) case "purple" : print ("红色和蓝色的混合" ) case "green" : print ("蓝色和黄色的混合" ) default : print ("这可能不是辅助颜色" ) }
switch 语句:区间匹配 1 2 3 4 5 6 7 8 9 10 11 12 let year = 1905 var artPeriod: String switch year { case 1860 ... 1885 : artPeriod = "印象派" case 1886 ... 1910 : artPeriod = "后印象派" default : artPeriod = "未知" }
switch 语句:复合案例 1 2 3 4 5 6 7 8 9 10 11 12 13 let service = "Seamless" switch service { case "Uber" , "Lyft" : print ("旅行" ) case "DoorDash" , "Seamless" , "GrubHub" : print ("餐厅送餐" ) case "Instacart" , "FreshDirect" : print ("杂货配送" ) default : print ("未知服务" ) }
switch 语句:where 子句 1 2 3 4 5 6 7 8 9 10 11 12 let num = 7 switch num { case let x where x % 2 == 0 : print ("\(num) 是偶数" ) case let x where x % 2 == 1 : print ("\(num) 奇数" ) default : print ("\(num) 无效" ) }
逻辑运算符
逻辑运算符 && 1 2 3 4 true && true true && false false && true false && false
逻辑运算符 || 1 2 3 4 true || true true || false false || true false || false
组合逻辑运算符
!false && true
首先计算并返回 true
然后,表达式,true
|| false
评估并返回最终结果 true
true && false
首先计算返回 false
然后,表达式,false
|| false
评估并返回最终结果 false
控制执行顺序 1 2 3 4 5 6 7 true || true && false || false (true || true ) && (false || false )
简单的 guard 1 2 3 4 5 6 7 8 9 func greet (name : String ?) { guard let unwrapped = name else { print ("Hello guest!" ) return } print ("Hello \(unwrapped) !" ) } greet(name: "Asma" ) greet(name: nil )
循环 范围 1 2 let zeroToThree = 0 ... 3
stride() 函数 1 2 3 4 5 for num in stride (from: 1 , to: 5 , by: 2 ) { print (num) }
for-in 循环 1 2 3 4 5 6 7 for char in "hehe" { print (char) }
continue 关键字 1 2 3 4 5 6 7 8 9 for num in 0 ... 5 { if num % 2 == 0 { continue } print (num) }
continue
关键字将强制循环继续进行下一次迭代
break 关键字 1 2 3 4 5 6 7 8 9 10 11 for char in "supercalifragilistice" { if char == "c" { break } print (char) }
使用下划线 1 2 3 4 5 6 for _ in 1 ... 3 { print ("Olé" ) }
遍历指定范围 1 2 3 for i in 0 ... 10 { print (i) }
封闭指定范围操作符(…)
while 循环 1 2 3 4 5 6 7 8 var counter = 1 var stopNum = Int .random(in: 1 ... 10 )while counter < stopNum { print (counter) counter += 1 }
while
循环接受一个条件,并在所提供的条件为 true
时持续执行其主体代码。如果条件从不为假,则循环将继续运行,程序将陷入无限循环
repeate while 1 2 3 4 5 6 var counter = 1 repeat { print (counter) counter += 1 } while counter <= 5
至少执行一次
遍历字典对象 1 2 3 4 5 6 7 8 9 var myDictionary = [ "name" : "John" , "age" : 25 ] for (key, value) in myDictionary { print ("\(key) : \(value) " ) }
数组和集合 Array 数组
.count 属性 1 2 3 var grocery = ["🥓" , "🥞" , "🍪" , "🥛" , "🍊" ]print (grocery.count)
索引 索引是指项目在有序列表中的位置,使用下标语法 array[index]
从数组中检索单个元素。
1 2 3 4 5 6 7 var vowels = ["a" , "e" , "i" , "o" , "u" ]print (vowels[0 ]) print (vowels[1 ]) print (vowels[2 ]) print (vowels[3 ]) print (vowels[4 ])
注意:Swift 数组是零索引的,这意味着第一个元素的索引为 0。
用数组字面量初始化 1 2 3 4 var snowfall = [2.4 , 3.6 , 3.4 , 1.8 , 0.0 ]var temp: [Int ] = [33 , 31 , 30 , 38 , 44 ]
.append() 方法和 += 运算符 1 2 3 4 5 var gymBadges = ["Boulder" , "Cascade" ]gymBadges.append("Thunder" ) gymBadges += ["Rainbow" , "Soul" ]
.insert() 和 .remove() 方法 1 2 3 4 5 6 var moon = ["🌖" , "🌗" , "🌘" , "🌑" ]moon.insert("🌕" , at: 0 ) moon.remove(at: 4 )
遍历数组 1 2 3 4 5 6 7 var employees = ["小王" , "张三" , "王五" ]for person in employees { print (person) }
集合(Set) 1 2 3 4 5 var paintingsInMOMA: Set = [ "The Dream" , "The Starry Night" , "The False Mirror" ]
我们可以使用集合(Set
)来存储相同数据类型的唯一
元素
空集合(Set) 1 2 3 4 var team = Set <String >()print (team)
填充集合 1 var vowels: Set = ["a" , "e" , "i" , "o" ,"u" ]
要创建一个填充有值的集合,请在赋值运算符之前使用 Set
关键字。
.insert() 1 2 3 4 5 6 var cookieJar: Set = [ "Chocolate Chip" , "Oatmeal Raisin" ] cookieJar.insert("Peanut Butter Chip" )
.remove() 和 .removeAll() 方法 1 2 3 4 5 6 var oddNumbers: Set = [1 , 2 , 3 , 5 ]oddNumbers.remove(2 ) oddNumbers.removeAll()
.contains() 检测数组中的值 1 2 3 4 5 6 7 8 9 var names: Set = ["Rosa" , "Doug" , "Waldo" ]print (names.contains("Lola" )) if names.contains("Waldo" ){ print ("There's Waldo!" ) } else { print ("Where's Waldo?" ) }
迭代一个集合 1 2 3 4 5 var recipe: Set = ["蛋" , "面粉" , "糖" ]for ingredient in recipe { print ("在配方中包含\(ingredient) " ) }
.isEmpty 属性 1 2 3 4 5 var emptySet = Set <String >()print (emptySet.isEmpty) var populatedSet: Set = [1 , 2 , 3 ]print (populatedSet.isEmpty)
.count 属性 1 2 3 4 var band: Set = ["张三" , "王五" , "赵六" ]print ("乐队有 \(band.count) 名演奏者。" )
.intersection() 交叉 1 2 3 4 5 var setA: Set = ["A" , "B" , "C" , "D" ]var setB: Set = ["C" , "D" , "E" , "F" ]var setC = setA.intersection(setB)print (setC)
.union() 合并去重 1 2 3 4 5 6 var setA: Set = ["A" , "B" , "C" , "D" ]var setB: Set = ["C" , "D" , "E" , "F" ]var setC = setA.union(setB)print (setC)
.symmetricDifference() 对称差 1 2 3 4 5 6 var setA: Set = ["A" , "B" , "C" , "D" ]var setB: Set = ["C" , "D" , "E" , "F" ]var setC = setA.symmetricDifference(setB)print (setC)
.subtracting() 减法 1 2 3 4 5 6 var setA: Set = ["A" , "B" , "C" , "D" ]var setB: Set = ["C" , "D" ]var setC = setA.subtracting(setB)print (setC)
字典 基础字典 1 2 3 4 5 var dictionaryName = [ "Key1" : "Value1" , "Key2" : "Value2" , "Key3" : "Value3" ]
成对数据或键值对的无序
集合
Keys 1 2 3 4 5 var fruitStand = [ "Coconuts" : 12 , "Pineapples" : 12 , "Papaya" : 12 ]
每个键
都是唯一
的,即使它们都包含相同的值
类型一致性 1 2 3 4 5 var numberOfSides = [ "triangle" : 3 , "square" : 4 , "rectangle" : 4 ]
仅包含 String
键和 Int
值
初始化填充字典 1 2 3 4 5 var employeeID = [ "Hamlet" : 1367 , "Horatio" : 8261 , "Ophelia" : 9318 ]
初始化一个空字典 1 2 3 4 5 var yearlyFishPopulation = [Int : Int ]()var yearlyBirdPopulation: [Int : Int ] = [:]
添加到字典 1 2 3 4 5 6 var pronunciation = [ "library" : "lai·breh·ree" , "apple" : "a·pl" ] pronunciation["programming" ] = "prow·gra"
删除键值对 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var bookShelf = [ "Goodnight" : "Margaret Wise Brown" , "The BFG" : "Roald Dahl" , "Falling Up" : "Shel Silverstein" , "No, David!" : "David Shannon" ] bookShelf["The BFG" ] = nil bookShelf.removeValue(forKey: "Goodnight" ) bookShelf.removeAll()
修改键值对 1 2 3 4 5 6 7 8 9 10 11 var change = [ "Quarter" : 0.29 , "Dime" : 0.15 , "Nickel" : 0.05 ] change["Quarter" ] = .25 change.updateValue(.10 , forKey: "Dime" )
要更改键值对的值,请使用 .updateValue()
方法或下标语法,通过将括号 [ ]
和其中的现有键附加到字典的名称,然后添加赋值运算符 (=
) 后跟修改后的值
.isEmpty 属性 1 2 3 4 5 6 7 var bakery = [String :Int ]()print (bakery.isEmpty) bakery["Cupcakes" ] = 12 print (bakery.isEmpty)
.count 属性 1 2 3 4 5 var fruitStand = [ "Apples" : 12 , "Oranges" , 17 ] print (fruitStand.count)
为变量赋值 1 2 3 4 5 6 7 8 9 10 11 12 13 var hex = [ "red" : "#ff0000" , "yellow" : "#ffff00" , "blue" : "#0000ff" , ] print ("蓝色十六进制代码 \(hex["blue" ]) " )if let redHex = hex["red" ] { print ("红色的十六进制代码 \(redHex) " ) }
将键值对的值分配给变量将返回一个可选值。要提取值,请使用可选的展开
遍历字典 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 var emojiMeaning = [ "🤔" : "Thinking Face" , "😪" : "Sleepy Face" , "😵" : "Dizzy Face" ] for (emoji, meaning) in emojiMeaning { print ("\(emoji) 被称为'\(meaning) Emoji'" ) } for emoji in emojiMeaning.keys { print (emoji) } for meaning in emojiMeaning.values { print (meaning) }
函数 基础函数 1 2 3 4 5 6 func washCar () -> Void { print ("Soap" ) print ("Scrub" ) print ("Rinse" ) print ("Dry" ) }
返回值为空的函数(void)
调用函数 1 2 3 4 5 6 func greetLearner () { print ("欢迎来到 Quick Reference!" ) } greetLearner()
返回值 1 2 3 4 5 6 7 8 let birthYear = 1994 var currentYear = 2020 func findAge () -> Int { return currentYear - birthYear } print (findAge())
多个参数 1 2 3 4 5 6 func convertFracToDec (numerator : Double , denominator : Double ) -> Double { return numerator / denominator } let decimal = convertFracToDec(numerator: 1.0 , denominator: 2.0 ) print (decimal)
省略参数标签 1 2 3 4 5 func findDiff (_ a : Int , b : Int ) -> Int { return a - b } print (findDiff(6 , b: 4 ))
返回多个值 1 2 3 4 5 6 7 8 9 func smartphoneModel () -> (name: String , version: String , yearReleased: Int ) { return ("iPhone" , "8 Plus" , 2017 ) } let phone = smartphoneModel()print (phone.name) print (phone.version) print (phone.yearReleased)
Parameters & Arguments 1 2 3 4 5 6 7 8 9 func findSquarePerimet (side : Int ) -> Int { return side * 4 } let perimeter = findSquarePerimet(side: 5 )print (perimeter)
隐式返回 1 2 3 4 5 6 func nextTotalSolarEclipse () -> String { "April 8th, 2024 🌎" } print (nextTotalSolarEclipse())
默认参数 1 2 3 4 5 func greet (person : String = "guest" ) { print ("Hello \(person) " ) } greet() greet(person: "Aliya" )
输入输出参数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 var currentSeason = "冬天" func season (month :Int , name :inout String ) { switch month { case 1 ... 2 : name = "冬天 ⛄️" case 3 ... 6 : name = "春天 🌱" case 7 ... 9 : name = "夏天 ⛱" case 10 ... 11 : name = "秋天 🍂" default : name = "未知" } } season(monthNum: 4 , name: & currentSeason) print (currentSeason)
可变参数 1 2 3 4 5 6 7 func totalStudent (data : String ...) -> Int { let numStudents = data.count return numStudents } print (totalStudent(data: "王五" , "张三" ))
可选参数 1 2 3 func getFirstInitial (from name : String ?) -> String ? { return name? .first }
函数可以接受可选类型并返回可选类型。当一个函数不能返回请求类型的合理实例时,它应该返回 nil
省略 return 关键字 1 2 3 func multiply (x : Int , y : Int ) -> Int { x * y }
额外指定参数命名标签 1 2 3 4 5 6 7 8 9 10 11 12 13 func calculate (of numbers : Int ...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } let result = calculate(of: 1 , 2 , 3 , 4 , 5 )print ("Sum: \(result) " )
函数作为参数 1 2 3 4 5 6 7 8 9 10 11 12 13 func doMath ( operation : (Int , Int ) -> Int , a : Int , b : Int ) -> Int { return operation(a, b) } func add (_ a : Int , _ b : Int ) -> Int { return a + b } let result = doMath(5 , 3 , operation: add)print ("Addition Result: \(result) " )
闭包 1 2 3 4 5 6 let add: (Int , Int ) -> Int = { (a, b) in return a + b } let result = add(3 , 5 )print ("Sum: \(result) " )
结构 结构创建 1 2 3 4 5 6 7 8 9 struct Building { var address: String var floors: Int init (address : String , floors : Int ) { self .address = address self .floors = floors } }
结构或结构用于以编程方式在代码中表示现实生活中的对象。结构是使用 struct
关键字创建的,后跟其名称,然后是包含其属性和方法的主体
默认属性值 1 2 3 4 5 6 7 8 9 struct Car { var numOfWheels = 4 var topSpeed = 80 } var reliantRobin = Car (numOfWheels: 3 )print (reliantRobin.numOfWheels) print (reliantRobin.topSpeed)
结构实例创建 1 2 3 4 5 6 7 8 9 10 11 12 struct Person { var name: String var age: Int init (name : String , age : Int ) { self .name = name self .age = age } } var morty = Person (name: "张三" , age: 14 )
init() 方法 1 2 3 4 5 6 7 8 9 struct TV { var size: Int var type: String init (size : Int , type : String ) { self .size = size self .type = type } }
使用 TV
类
1 var newTV = TV (size: 65 , type: "LED" )
检查类型 1 2 print (type (of: "abc" )) print (type (of: 123 ))
变异方法(mutating) 1 2 3 4 5 6 struct Menu { var menuItems = ["Fries" , "Burgers" ] mutating func addToMenu (dish : String ) { self .menuItems.append(dish) } }
使用 Menu
类
1 2 3 4 var dinerMenu = Menu ()dinerMenu.addToMenu(dish: "Toast" ) print (dinerMenu.menuItems)
结构方法 1 2 3 4 5 6 7 struct Dog { func bark () { print ("Woof" ) } } let fido = Dog ()fido.bark()
Class 引用类型(类) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Player { var name: String init (name : String ) { self .name = name } } var player1 = Player (name: "Tomoko" )var player2 = player1player2.name = "Isabella" print (player1.name) print (player2.name)
类的实例 1 2 3 4 5 6 7 class Person { var name = "" var age = 0 } var sonny = Person ()
init() 方法 1 2 3 4 5 6 7 8 class Fruit { var hasSeeds = true var color: String init (color : String ) { self .color = color } }
使用 Fruit 类
1 let apple = Fruit (color: "red" )
可以使用 init()
方法和相应的初始化属性来初始化类,在 init()
方法中,self
关键字用于引用类分配属性值的实际实例
类属性 1 2 3 4 5 6 var ferris = Student ()ferris.name = "Ferris Bueller" ferris.year = 12 ferris.gpa = 3.81 ferris.honors = false
继承 假设我们有一个 BankAccount 类:
1 2 3 4 5 6 7 8 9 class BankAccount { var balance = 0.0 func deposit (amount : Double ) { balance += amount } func withdraw (amount : Double ) { balance -= amount } }
SavingsAccount
继承 BankAccount
类
1 2 3 4 5 6 7 8 class SavingsAccount : BankAccount { var interest = 0.0 func addInterest () { let interest = balance * 0.005 self .deposit(amount: interest) } }
新的 SavingsAccount
类(子类)自动获得了 BankAccount
类(超类)的所有特征。 此外,SavingsAccount
类定义了一个 .interest
属性和一个 .addInterest()
方法。
示例 使用数据类型
1 2 3 4 5 6 class Student { var name: String var year: Int var gpa: Double var honors: Bool }
使用默认属性值
1 2 3 4 5 class Student { var name = "" var gpa = 0.0 var honors = false }
这是结构定义和类定义的示例 1 2 3 4 5 6 7 8 9 10 struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution () var interlaced = false var frameRate = 0.0 var name: String ? }
Resolution
结构定义和 VideoMode
类定义仅描述 Resolution
或 VideoMode
的外观,创建结构或类的实例:
1 2 let resolution = Resolution (width: 1920 )let someVideoMode = VideoMode ()
类的扩展 1 2 3 4 5 6 extension String { var boolValue: Bool { return self == "1" } } let isTure = "0" .boolValue
枚举 定义枚举 1 2 3 4 5 6 7 8 9 10 11 enum Day { case monday case tuesday case wednesday case thursday case friday case saturday case sunday } let casualWorkday: Day = .friday
Switch 语句 1 2 3 4 5 6 7 8 9 10 11 12 13 14 enum Dessert { case cake(flavor: String ) case vanillaIceCream(scoops: Int ) case brownie } let custom: Dessert = .cake(flavor: "红色" )switch custom { case let .cake(flavor): print ("你点了一个 \(flavor) 蛋糕" ) case .brownie: print ("你点了一块巧克力蛋糕" ) }
CaseIterable 1 2 3 4 5 6 7 8 9 10 enum Season : CaseIterable { case winter case spring case summer case fall } for season in Season .allCases { print (season) }
添加对 CaseIterable
协议的一致性以访问 allCases
属性,该属性返回枚举的所有案例的数组
原始值 1 2 3 4 5 6 enum Beatle : String { case john, paul, george, ringo } print ("披头士是 \(Beatle.john.rawValue) ." )
相关值 1 2 3 4 5 6 7 enum Dessert { case cake(flavor: String ) case vanillaIceCream(scoops: Int ) case brownie } let order: Dessert = .cake(flavor: "红色" )
枚举的可赋值性 1 2 3 4 5 enum Content { case empty case text(String ) case number(Int ) }
使用 switch 处理可赋值枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 let content = Content .text("Hello" )switch content { case .empty: print ("Value is empty" ) case .text(let value): print ("Value is \(value) " ) case .number(_ ): print ("Value is a number" ) } if case .text(let value) = content { print ("Value is \(value) " ) }
从原始值初始化 1 2 3 4 5 6 7 8 9 enum Hello : String { case english = "Hello" case japanese = "你好呀!" case emoji = "👋" } let hello1 = Hello (rawValue: "你好呀!" )let hello2 = Hello (rawValue: "Привет" )print (hello1) print (hello2)
计算属性 1 2 3 4 5 6 7 8 9 enum ShirtSize : String { case small = "S" case medium = "M" case large = "L" case extraLarge = "XL" var description: String { return "这件衬衫尺码是 \(self .rawValue) " } }
遍历字符串 1 2 3 4 5 enum Currency : String { case euro = "EUR" case dollar = "USD" case pound = "GBP" }
输出枚举的原始值
1 2 let euroSymbol = Currency .euro.rawValueprint ("欧元的货币符号是 \(euroSymbol) " )
实例方法 1 2 3 4 5 6 7 8 enum Traffic { case light case heavy mutating func reportAccident () { self = .heavy } }
枚举也可以有实例方法
1 2 3 var currentTraffic: Traffic = .lightcurrentTraffic.reportAccident()
实例方法改变了枚举的值,则需要将其标记为 mutating
扩展 声明扩展 1 2 3 4 5 6 7 8 9 10 11 struct Person { var name: String var age: Int func eat () {} } extension Person { } extension Person : SomeProtocol { }
扩展构造器 1 2 3 4 5 6 7 8 9 10 11 12 extension CGRect { init (center : CGPoint , size : CGSize ) { let x: CGFloat = center.x - size.width * 0.5 let y: CGFloat = center.y - size.height * 0.5 self .init (origin: CGPoint (x: x, y: y), size: size) } } let frame = CGRect (center: CGPoint (x: 100 , y: 100 ), size: CGSize (width: 50 , height: 50 )) print ("Origin is \(frame.origin) " )
扩展可变实例方法 1 2 3 4 5 6 7 8 extension Double { mutating func cube () { self = self * self * self } } var boxCube: Double = 2.0 boxCube.cube() print (boxCube)
扩展方法 1 2 3 4 5 6 7 8 9 extension String { func deletingPrefix (_ prefix : String ) -> String { guard self .hasPrefix(prefix ) else { return self } return String (self .dropFirst(prefix .count)) } } print ("Hello World" .deletingPrefix("He" ))
扩展计算属性 1 2 3 4 5 6 7 8 9 10 extension Double { var km: Double { self * 1000 } var m: Double { self } var cm: Double { self / 100.0 } var mm: Double { self / 1000.0 } } let metric: Double = 30.48 .cmprint ("1 metric is \(metric.m) meter" )print ("1 metric is \(metric.km) kilometer" )
扩展存储属性 1 2 3 4 5 6 7 8 9 10 11 12 private var fuchsiaKey = "fuchsiaKey" extension UIColor { var fuchsia: UIColor ? { get { return objc_getAssociatedObject(self , & fuchsiaKey) as? UIColor } set { objc_setAssociatedObject(self , & fuchsiaKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } }
另见