Swift基础
程序员文章站
2022-03-01 17:01:20
...
Type Aliases
typealias AudioSample = UInt16
Tuples(元组)
let http404Error = (404, "Not Found")
使用方法
对多个对象进行赋值:
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"
通过index获取Tuples成员
print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"
命名Tuples成员
let http200Status = (statusCode: 200, description: "OK")
// 获取成员方法
print("The status code is \(http200Status.statusCode)")
// Prints "The status code is 200"
print("The status message is \(http200Status.description)")
// Prints "The status message is OK"
Optional Binding
用在if
和while
判断条件里面,避免对optionals
对象的展开(!):
if let constantName = someOptional {
statements
}
if let actualNumber = Int(possibleNumber) {
print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
print("\"\(possibleNumber)\" could not be converted to an integer")
}
// Prints ""123" has an integer value of 123"
Implicitly Unwrapped Optionals
在声明的类型后面加!
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation mark
Error Handling
catch
语法
func makeASandwich() throws {
// ...
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}
Assertions(断言) and Preconditions(前置条件)
区别:断言只在debug模式下起作用,前置条件在debug和release下都起作用
// 断言
let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 is not >= 0.
// 前置条件
// In the implementation of a subscript...
precondition(index > 0, "Index must be greater than zero.")
Lazy Stored Properties
在第一次引用到的时候才初始化,注意:在多线程中,同时进行第一次引用的时候,不保证属性只初始化一次。
class DataImporter {
/*
DataImporter is a class to import data from an external file.
The class is assumed to take a nontrivial amount of time to initialize.
*/
var filename = "data.txt"
// the DataImporter class would provide data importing functionality here
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()
// the DataManager class would provide data management functionality here
}
let manager = DataManager()
manager.data.append("Some data")
manager.data.append("Some more data")
// the DataImporter instance for the importer property has not yet been created
print(manager.importer.filename)
// the DataImporter instance for the importer property has now been created
// Prints "data.txt"
上一篇: Swift基础
下一篇: Array.fill()使用记录