以下文章来源于知识小集 ,作者Lorenzo Boaro
大前端开源框架、开源应用、工具、跨平台方案推荐
本文翻译自 raywenderlich 教程 Swift 5.1 Cheat Sheet and Quick Reference (https://www.raywenderlich.com/6362977-swift-5-1-cheat-sheet-and-quick-reference) ,请参考原文阅读
let double: Double = 2.0
// double = 3.0 // 错误:不能给常量重新赋值
let inferredDouble = 2.0 // 推断为一个 Double 类型
var mutableInt: Int = 1
mutableInt = 2 // OK: 可以给一个变量重新赋值
let integerValue = 8
let doubleValue = 8.0
//let sum = integerValue + double // 错误:类型不匹配
let sum = Double(integerValue) + double // OK: 两个值有相同类型
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)") // 插入一个 Double 值
print("This is my opinion: \(mutableString)") // 插入一个字符串
let httpError = (503, "Server Error")
let (code, reason) = httpError
// 另一种分解方式
let codeByIndex = httpError.0
let reasonByIndex = httpError.1
let (_, justTheReason) = httpError
var catchphrase: String? // 由编译器自动设置为nil
catchphrase = "Hey, what's up, everybody?"
// 如果 catchphrase 不是nil,count1 包含 catchphrase 的计数值;
// 否则程序崩溃
let count1: Int = catchphrase!.count
// 如果 catchphrase?.count 返回的可选 Int 包含一个值,
// 则将一个称为 count 的新常量设置为可选中包含的值
if let count = catchphrase?.count {
print(count)
}
// 如果 catchphrase 不是 nil,count2 包含 catchphrase 的 count 值;否则为 0
let count2: Int = catchphrase?.count ?? 0
// 如果 catchphrase 不是nil,count3 包含 catchphrase 的 count 值;否则为 nil
let count3: Int? = catchphrase?.count
let forcedCatchphrase: String! = "Hey, what's up, everybody?"
let implicitCatchphrase = forcedCatchphrase // 无需使用感叹号
let immutableArray: [String] = ["Alice", "Bob"]
// mutableArray 的类型为 [String]
var mutableArray = ["Eve", "Frank"]
let isEveThere = immutableArray.contains("Eve")
let name: String = immutableArray[0] // 通过索引访问
// 如果索引越界,则崩溃
mutableArray[1] = "Bart"
// immutableArray[1] = "Bart" // 错误:不能修改
mutableArray.append("Ellen") // 添加项目
mutableArray.insert("Gemma", at: 1) // 在指定索引处添加项目
// 不能重新赋值一个常量集合或修改它的内容
// 可以重新赋值一个可变集合和修改它的w内容
mutableArray = ["Ilary", "David"]
mutableArray[0] = "John"
let removedPerson = mutableArray.remove(at: 1)
let immutableDict: [String: String] = ["name": "Kirk", "rank": "captain"]
// mutableDict 的类型为 [String: String]
var mutableDict = ["name": "Picard", "rank": "captain"]
let name2: String? = immutableDict["name"]
mutableDict["name"] = "Janeway"
mutableDict["ship"] = "Voyager"
let rankWasRemoved: String? = mutableDict.removeValue(forKey: "rank")
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) // 0 to 10
}
// 半开区间操作符(..<)
for i in 0..<10 {
print(i) // 0 to 9
}
var x = 0
while x < 10 {
x += 1
print(x)
}
repeat {
x -= 1
print(x)
} while(x > 0)
let number = 88
if (number <= 10) {
// 如果 number <= 10, 则执行这里
} else if (number > 10 && number < 100) {
// 如果 number > 10 && number < 100, 则执行这里
} else {
// 否则执行这里
}
// if-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:
// 如果 year 是 2003 或者 2004,则执行这个语句
print("Panther or Tiger")
case 2010:
// 如果 year 的值是 2010,则执行这个语句
print("Lion")
case 2012...2015:
// 如果 year 在 2012-2015 范围内(包含边界值),则执行这个语句
print("Mountain Lion through El Captain")
default: // 每个 switch 语句必须涵盖所有情况
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)
}
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)
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): // 提取 String 值
print("Value is \(value)")
case .number(_): // 忽略 Int 值
print("Value is a number")
}
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")
class Person {
let name: String
// 类构造器
init(name: String) {
self.name = name
}
// 使用 deinit 来执行对象资源清理操作
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
// 重写 isHappy 计算属性,以提供额外逻辑
override var isHappy: Bool {
numberOfLaughs > 0 && numberOfExams > 2
}
}
let ray = Student(name: "Ray")
ray.numberOfExams = 4
ray.laugh()
//let happy = ray.isHappy
final class Child: Person { }
// 一个类需要至少一个指定构造器
// 同时可以有一个或多个便捷构造器
class ModeOfTransportation {
let name: String
// 定义一个指定构造器
// 其携带一个名为 name 的参数
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)
}
}
extension String {
// 扩展 String 类型来计算一个 String 实例是真还是假
var boolValue: Bool {
if self == "1" {
return true
}
return false
}
}
let isTrue = "0".boolValue
enum BeverageMachineError: Error {
case invalidSelection
case insufficientFunds
case outOfStock
}
func selectBeverage(_ selection: Int) throws -> String {
// Some logic here
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)
public class AccessLevelsShowcase { // 可以从其它模块中访问类
public var somePublicProperty = 0 // 可以从其它模块中访问该属性
var someInternalProperty = 0 // 可以在包含该类的块中访问该属性
fileprivate func someFilePrivateMethod() {} // 可以从定义该类的源文件中访问该属性
private func somePrivateMethod() {} // 可以在该类的代码块中访问该属性
}
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)
推荐↓↓↓
长
按
关
注
👉【16个技术公众号】都在这里!
涵盖:程序员大咖、源码共读、程序员共读、数据结构与算法、黑客技术和网络安全、大数据科技、编程前端、Java、Python、Web编程开发、Android、iOS开发、Linux、数据库研发、幽默程序员等。