A Swift Tour
最后更新于:2022-04-01 02:48:29
## A Swift Tour
Functions are actually a special case of closures. (In Swift, functions are just named closures) You can write a closure without a name by surrounding code with braces (`{}`). Use `in` to separate the arguments and return type from the body.
Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method.
~~~
// 错误
let convertedRank = Rank.fromRaw(3) // convertedRank 的类型是Rank?
let threeDescription = convertedRank.toRaw() // optional type不能直接方法
//正确
let convertedRank = Rank.fromRaw(3)!
let threeDescription = convertedRank.toRaw() // 3
// 正确
let convertedRank = Rank.fromRaw(3)
let threeDescription = convertedRank!.toRaw() // 3
// 正确
let convertedRank = Rank.fromRaw(3)
let threeDescription = convertedRank?.toRaw() // {some 3}
~~~
One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference
结构体中的方法要修改结构体,需要加mutating关键字;类则不用,加了反而错误。
Use `extension` to add functionality to an existing type, such as new methods and computed properties. You can use an extension to add protocol conformance to a type that is declared elsewhere, or even to a type that you imported from a library or framework.
~~~
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
7.simpleDescription
~~~
You can use a protocol name just like any other named type—for example, to create a collection of objects that have different types but that all conform to a single protocol. When you work with values whose type is a protocol type, methods outside the protocol definition are not available.
~~~
let protocolValue: ExampleProtocol = a // a is an instance of SimpleClass, and SimpleClass adopt ExampleProtocol
protocolValue.simpleDescription
// protocolValue.anotherProperty // Uncomment to see the error
~~~
Even though the variable protocolValue has a runtime type of SimpleClass, the compiler treats it as the given type of ExampleProtocol. This means that you can’t accidentally access methods or properties that the class implements in addition to its protocol conformance.