参考:Swift 5.1 Cheat Sheet and Quick Reference
声明常量和变量
let double: Double = 2.0
let inferredDouble = 2.0
var mutableInt: Int = 1
mutableInt = 2
数值类型转换
let integerValue = 8
let doubleValue = 8.0
let sum = Double(integerValue) + double
String 字符串
let helloWorld = "Hello, World!"
let helloWorldProgram = """
A "Hello, World!" program generally is a computer program
that outputs or displays the message "Hello, World!"
"""
let emptyString = ""
let anotherEmptyString = String()
var mutableString = "Swift"
mutableString += " is awesome!"
print("The value is \(double)")
print("This is my opinion: \(mutableString)")
Tuples 元组
let httpError = (503, "Server Error")
let (code, reason) = httpError
let codeByIndex = httpError.0
let reasonByIndex = httpError.1
let (_, justTheReason) = httpError
Optionals 可选类型
var catchphrase: String?
catchphrase = "Hey, what's up, everybody?"
let count1: Int = catchphrase!.count
if let count = catchphrase?.count {
print(count)
}
let count2: Int = catchphrase?.count ?? 0
let count3: Int? = catchphrase?.count
let forcedCatchphrase: String! = "Hey, what's up, everybody?"
let implicitCatchphrase = forcedCatchphrase
集合类型: Array
let immutableArray: [String] = ["Alice", "Bob"]
var mutableArray = ["Eve", "Frank"]
let isEveThere = immutableArray.contains("Eve")
let name: String = immutableArray[0]
mutableArray[1] = "Bart"
mutableArray.append("Ellen")
mutableArray.insert("Gemma", at: 1)
let removedPerson = mutableArray.remove(at: 1)
mutableArray = ["Ilary", "David"]
mutableArray[0] = "John"
集合类型: Dictionary
let immutableDict: [String: String] = ["name": "Kirk", "rank": "captain"]
var mutableDict = ["name": "Picard", "rank": "captain"]
let name2: String? = immutableDict["name"]
mutableDict["name"] = "Janeway"
mutableDict["ship"] = "Voyager"
let rankWasRemoved: String? = mutableDict.removeValue(forKey: "rank")
集合类型: Set
let immutableSet: Set = ["chocolate", "vanilla", "chocolate"]
var mutableSet: Set = ["butterscotch", "strawberry"]
immutableSet.contains("chocolate")
mutableSet.insert("green tea")
let flavorWasRemoved: String? = mutableSet.remove("strawberry")
控制流: 循环
for item in listOrSet {
print(item)
}
for (key, value) in dictionary {
print("\(key) = \(value)")
}
for i in 0...10 {
print(i)
}
for i in 0..<10 {
print(i)
}
var x = 0
while x < 10 {
x += 1
print(x)
}
repeat {
x -= 1
print(x)
} while(x > 0)
控制流: 条件语句
let number = 88
if (number <= 10) {
} else if (number > 10 && number < 100) {
} else {
}
let height = 100
let isTall = height > 200 ? true : false
for n in 1...30 {
guard n % 2 == 0 else {
continue
}
print("\(n) is even")
}
let year = 2012
switch year {
case 2003, 2004:
print("Panther or Tiger")
case 2010:
print("Lion")
case 2012...2015:
print("Mountain Lion through El Captain")
default:
print("Not already classified")
}
函数
func sayHello() {
print("Hello")
}
func sayHello(name: String) {
print("Hello \(name)!")
}
func sayHello(name: String = "Lorenzo") {
print("Hello \(name)!")
}
func sayHello(name: String = "Lorenzo", age: Int) {
print("\(name) is \(age) years old!")
}
sayHello(age: 35)
func add(x: Int, y: Int) -> Int {
return x + y
}
let value = add(x: 8, y: 10)
func multiply(x: Int, y: Int) -> Int {
x + y
}
func add(x xVal: Int, y yVal: Int) -> Int {
return xVal + yVal
}
func add(_ x: Int, y: Int) -> Int {
return x + y
}
let value = add(8, y: 10)
func doMath(operation: (Int, Int) -> Int, a: Int, b: Int) -> Int {
return operation(a, b)
}
Closures 闭包
let adder: (Int, Int) -> Int = { (x, y) in x + y }
let square: (Int) -> Int = { $0 * $0 }
let addWithClosure = doMath(operation: adder, a: 2, b: 3)
Enumerations 枚举类型
enum Taste {
case sweet, sour, salty, bitter, umami
}
let vinegarTaste = Taste.sour
enum Food: CaseIterable {
case pasta, pizza, hamburger
}
for food in Food.allCases {
print(food)
}
enum Currency: String {
case euro = "EUR"
case dollar = "USD"
case pound = "GBP"
}
let euroSymbol = Currency.euro.rawValue
print("The currency symbol for Euro is \(euroSymbol)")
enum Content {
case empty
case text(String)
case number(Int)
}
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")
}
Structs 结构体
struct User {
var name: String
var age: Int = 40
}
let john = User(name: "John", age: 35)
let dave = User(name: "Dave")
print("\(john.name) is \(john.age) years old")
Classes 类
class Person {
let name: String
init(name: String) {
self.name = name
}
deinit {
print("Perform the deinitialization")
}
var numberOfLaughs: Int = 0
func laugh() {
numberOfLaughs += 1
}
var isHappy: Bool {
return numberOfLaughs > 0
}
}
let david = Person(name: "David")
david.laugh()
let happy = david.isHappy
class Student: Person {
var numberOfExams: Int = 0
override var isHappy: Bool {
numberOfLaughs > 0 && numberOfExams > 2
}
}
let ray = Student(name: "Ray")
ray.numberOfExams = 4
ray.laugh()
final class Child: Person { }
class ModeOfTransportation {
let name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "Not classified")
}
}
class Vehicle: ModeOfTransportation {
let wheels: Int
init(name: String, wheels: Int) {
self.wheels = wheels
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, wheels: 4)
}
}
Extensions 扩展
extension String {
var boolValue: Bool {
if self == "1" {
return true
}
return false
}
}
let isTrue = "0".boolValue
Error handling 错误处理
enum BeverageMachineError: Error {
case invalidSelection
case insufficientFunds
case outOfStock
}
func selectBeverage(_ selection: Int) throws -> String {
return "Waiting for beverage..."
}
let message: String
do {
message = try selectBeverage(20)
} catch BeverageMachineError.invalidSelection {
print("Invalid selection")
} catch BeverageMachineError.insufficientFunds {
print("Insufficient funds")
} catch BeverageMachineError.outOfStock {
print("Out of stock")
} catch {
print("Generic error")
}
let nillableMessage = try? selectBeverage(10)
let throwableMessage = try! selectBeverage(10)
Access Control 访问控制
public class AccessLevelsShowcase {
public var somePublicProperty = 0
var someInternalProperty = 0
fileprivate func someFilePrivateMethod() {}
private func somePrivateMethod() {}
}
Coding Protocols Coding 协议
import Foundation
struct UserInfo: Codable {
let username: String
let loginCount: Int
}
extension UserInfo: CustomStringConvertible {
var description: String {
return "\(username) has tried to login \(loginCount) time(s)"
}
}
let json = """
{ "username": "David", "loginCount": 2 }
"""
let decoder = JSONDecoder()
let data = json.data(using: .utf8)!
let userInfo = try! decoder.decode(UserInfo.self, from: data)
print(userInfo)
let encoder = JSONEncoder()
let userInfoData = try! encoder.encode(userInfo)
let jsonString = String(data: userInfoData, encoding: .utf8)!
print(jsonString)