- 原文地址:Swift + Keywords (V 3.0.1)
- 原文做者:Jordan Morgan
- 譯文出自:掘金翻譯計劃
- 譯者:Deepmissea
- 校對者:ylq167,oOatuo
Macbook + 紙張。致命組合javascript
有句話之前說過,如今我要再次提一下,一個優秀的匠人,他(她)的工具一樣優秀。當咱們一絲不苟地去使用這些工具時,它們就會帶咱們到想去的地方,或者完成咱們的求之不得的做品。html
我並無貶義的意思,由於老是有不少東西要學。因此今天,咱們來看看 Swift 中的每個關鍵字(v 3.0.1),看看它爲咱們每一個人提供的代碼,咱們每一個人預約的工具的名字。java
有一些是很簡單的,有一些是晦澀難懂的,也有一些是有點能認出來的。可是他們都很值得閱讀和學習,這會很漫長,準備好了嗎?ios
如今,讓咱們嗨起來~git
associatedtype:一般做爲協議的一部分,爲一種類型提供一個佔位符。在協議未被遵照以前,這個類型都是未知的。github
protocol Entertainment
{
associatedtype MediaType
}
class Foo : Entertainment
{
typealias MediaType = String // 能夠是任何符合需求的類型?
}複製代碼
class:一個構建程序代碼的通用且靈活的基礎結構。和 struct 有些類似,除了:express
class Person {
var name:String
var age:Int
var gender:String
}複製代碼
deinit:在類的實例被釋放前立刻調用。swift
class Person {
var name:String
var age:Int
var gender:String
deinit
{
// 從堆裏釋放,在這裏卸貨。
}
}複製代碼
enum:爲一組相關值定義通用類型,並使你可以在代碼中以類型安全的方式使用這些值。在 Swift 中,它們屬於第一類類型,而且可使用一些特性,這些特性在其餘語言裏每每只有類才支持。c#
enum Gender
{
case male
case female
}複製代碼
extension:容許爲現有的類、結構體、枚舉或協議添加新的功能。數組
class Person {
var name:String = ""
var age:Int = 0
var gender:String = ""
}
extension Person
{
func printInfo()
{
print("My name is \(name), I'm \(age) years old and I'm a \(gender).")
}
}複製代碼
fileprivate:訪問控制結構,將做用域限制在源文件。
class Person {
fileprivate var jobTitle:String = ""
}
extension Person
{
// 若是使用 "private" 聲明,將不會經過編譯。
func printJobTitle()
{
print("My job is \(jobTitle)")
}
}複製代碼
func : 執行一個特定的自包含的代碼塊。
func addNumbers(num1:Int, num2:Int) -> Int
{
return num1+num2
}複製代碼
import:將一個已構建的框架或應用,做爲一個單元暴露給指定的二進制文件。
import UIKit
// 如今,全部 UIKit 的代碼均可以調用
class Foo {}複製代碼
init : 構造一個類、結構體或枚舉的實例的過程。
class Person {
init()
{
// 在這設置默認的值等等。
}
}複製代碼
inout:傳遞給函數一個值,而後修改它,它會被傳回原來的位置來代替原始值。適用於引用類型和值類型。
func dangerousOp(_ error:inout NSError?)
{
error = NSError(domain: "", code: 0, userInfo: ["":""])
}
var potentialError:NSError?
dangerousOp(&potentialError)
// 如今 potentialError 被初始化了,再也不是 nil 了複製代碼
internal:訪問控制結構,容許實體在它定義模塊的任何源文件中使用,但不能在其外部的源文件中使用。
class Person {
internal var jobTitle:String = ""
}
let aPerson = Person()
aPerson.jobTitle = "This can set anywhere in the application"複製代碼
let:定義一個不可變的變量。
let constantString = "This cannot be mutated going forward"複製代碼
open:訪問控制結構,容許對象在定義的模塊以外被訪問或子類化。對於成員,外部模塊也是能夠訪問和覆蓋的。
open var foo:String? // 應用的內外均可以訪問或覆蓋,編寫框架時,是很經常使用的訪問控制符複製代碼
operator:一個用來檢查、更改或合併值的特殊符號或短語。
// 「-」 一元運算符,減小目標的值
let foo = 5
let anotherFoo = -foo // anotherFoo 如今是 -5 了
// 」+「 組合兩個值
let box = 5 + 3
// 」&&「 邏輯運算符,用來組合兩個布爾值
if didPassCheckOne && didPassCheckTwo
// 三元運算符,包含三個值?
let isLegalDrinkingAgeInUS:Bool = age >= 21 ? true : false複製代碼
private:訪問控制結構,把實體的做用域限制在聲明的位置。
class Person {
private var jobTitle:String = ""
}
extension Person
{
// 不會被編譯,jobTitle 的做用域只在 Person 類裏
func printJobTitle()
{
print("My job is \(jobTitle)")
}
}複製代碼
protocol:定義適合特定任務或部分功能的類、屬性和其餘需求的藍圖。
protocol Blog
{
var wordCount:Int { get set }
func printReaderStats()
}
class TTIDGPost : Blog
{
var wordCount:Int
init(wordCount:Int)
{
self.wordCount = wordCount
}
func printReaderStats()
{
// 打印一些統計信息
}
}複製代碼
public:訪問控制結構,容許對象在被定義的模塊內部訪問或子類化,對於成員,也只能夠在定義的模塊內部能夠訪問和覆蓋。
public var foo:String? // 在程序內部的任何地方均可以被覆蓋或重寫,可是外部不行。複製代碼
static:定義該類型本身的調用方法。也用於定義其靜態成員。
class Person {
var jobTitle:String?
static func assignRandomName(_ aPerson:Person)
{
aPerson.jobTitle = "Some random job"
}
}
let somePerson = Person()
Person.assignRandomName(somePerson)
//somePerson.jobTitle is now "Some random job"複製代碼
struct:一個構建程序代碼的通用且靈活的基礎結構,也提供了成員的初始化方法。和 class
不一樣,他們在代碼中被傳遞的時候,永遠複製,而不會啓動自動引用計數。另外,他們也不能:
struct Person
{
var name:String
var age:Int
var gender:String
}複製代碼
subscript:訪問集合、列表或者序列的快捷方式。
var postMetrics = ["Likes":422, "ReadPercentage":0.58, "Views":3409]
let postLikes = postMetrics["Likes"]複製代碼
typealias:將現有的類型的命名做爲別名。
typealias JSONDictionary = [String: AnyObject]
func parseJSON(_ deserializedData:JSONDictionary){}複製代碼
var:定義一個可變的變量。
var mutableString = ""
mutableString = "Mutated"複製代碼
break:在結束一個循環,或者在 if
、switch
中使用。
for idx in 0...3
{
if idx % 2 == 0
{
//Exits the loop on the first even value
break
}
}複製代碼
case:求值,而後和 switch
提供的類型來比較的語句。
let box = 1
switch box
{
case 0:
print("Box equals 0")
case 1:
print("Box equals 1")
default:
print("Box doesn't equal 0 or 1")
}複製代碼
continue:結束循環語句的當前迭代,可是不終止循環語句的繼續執行。
for idx in 0...3
{
if idx % 2 == 0
{
//Immediately begins the next iteration of the loop
continue
}
print("This code never fires on even numbers")
}複製代碼
default:用來覆蓋在 case
結構中未被明肯定義的值。
let box = 1
switch box
{
case 0:
print("Box equals 0")
case 1:
print("Box equals 1")
default:
print("Covers any scenario that doesn't get addressed above.")
}複製代碼
defer:用來執行在程序控制轉移到做用域以外以前的代碼。
func cleanUpIO()
{
defer
{
print("This is called right before exiting scope")
}
//Close out file streams,etc.
}複製代碼
do:一個前置語句,用來處理一塊代碼運行的錯誤。
do
{
try expression
//statements
}
catch someError ex
{
//Handle error
}複製代碼
else:與 if
語句聯合使用,當條件爲真時執行代碼的一部分,當相同的條件爲假的時候執行另外一部分。
if 1 > val
{
print("val is greater than 1")
}
else
{
print("val is not greater than 1")
}複製代碼
fallthrough:在 switch
語句中,明確容許一個 case 執行完繼續執行下一個。
let box = 1
switch box
{
case 0:
print("Box equals 0")
fallthrough
case 1:
print("Box equals 0 or 1")
default:
print("Box doesn't equal 0 or 1")
}複製代碼
for:對序列進行迭代,例如數字的範圍、數組中的項或字符串裏的字符。和 in
關鍵字配對
for _ in 0..<3 { print ("This prints 3 times") }複製代碼
guard:在不知足一個或多個條件的狀況下,將程序控制轉移到做用域以外,同時還能夠拆包任何可選類型。
private func printRecordFromLastName(userLastName: String?)
{
guard let name = userLastName, userLastName != "Null" else
{
//Sorry Bill Null, find a new job
return
}
//Party on
print(dataStore.findByLastName(name))
}複製代碼
if:根據一個或者多個條件的值來執行代碼。
if 1 > 2
{
print("This will never execute")
}複製代碼
in:對序列進行迭代,例如數字的範圍、數組中的項或字符串裏的字符。和 for
關鍵字配對
for _ in 0..<3 { print ("This prints 3 times") }複製代碼
repeat:在考慮循環條件以前,執行一次循環裏的內容。
repeat
{
print("Always executes at least once before the condition is considered")
}
while 1 > 2複製代碼
return:當即打斷當前上下文的控制流,另外返回一個獲得的值(若是存在的話)。
func doNothing()
{
return //Immediately leaves the context
let anInt = 0
print("This never prints \(anInt)")
}複製代碼
and
func returnName() -> String?
{
return self.userName //Returns the value of userName
}複製代碼
switch:考慮一個值,並與幾種可能的匹配模式進行比較。而後根據成功匹配的第一個模式,執行合適的代碼塊。
let box = 1
switch box
{
case 0:
print("Box equals 0")
fallthrough
case 1:
print("Box equals 0 or 1")
default:
print("Box doesn't equal 0 or 1")
}複製代碼
where:要求關聯的類型必須符合一個特定的協議,或者和某些特定的參數類型相同。它也用於提供一個額外的控制條件,來判斷一個模式是否符合控制表達式。where 子句能夠在多個上下文中使用,這些例子是 where 做爲從句和模式匹配的主要用途。
protocol Nameable
{
var name:String {get set}
}
func createdFormattedName<T:Nameable>(_ namedEntity:T) -> String where T:Equatable
{
//Only entities that conform to Nameable which also conform to equatable can call this function
return "This things name is " + namedEntity.name
}複製代碼
以及
for i in 0…3 where i % 2 == 0
{
print(i) //Prints 0 and 2
}複製代碼
while:執行一組語句,直到條件變爲 `false'。
while foo != bar
{
print("Keeps going until the foo == bar")
}複製代碼
Any:能夠用來表示任何類型的實例,包括函數類型。
var anything = [Any]()
anything.append("Any Swift type can be added")
anything.append(0)
anything.append({(foo: String) -> String in "Passed in \(foo)"})複製代碼
as:類型轉換運算符,用於嘗試將值轉換成不一樣的、預期的和特定的類型。
var anything = [Any]()
anything.append("Any Swift type can be added")
anything.append(0)
anything.append({(foo: String) -> String in "Passed in \(foo)" })
let intInstance = anything[1] as? Int複製代碼
或
var anything = [Any]()
anything.append("Any Swift type can be added")
anything.append(0)
anything.append({(foo: String) -> String in "Passed in \(foo)" })
for thing in anything
{
switch thing
{
case 0 as Int:
print("It's zero and an Int type")
case let someInt as Int:
print("It's an Int that's not zero but \(someInt)")
default:
print("Who knows what it is")
}
}複製代碼
catch:若是一個錯誤在 do
從句中被拋出,它會根據 catch
從句來匹配錯誤會如何被處理。摘自我以前的一篇關於 Swift 的錯誤處理文章。
do
{
try haveAWeekend(4)
}
catch WeekendError.Overtime(let hoursWorked)
{
print(「You worked \(hoursWorked) more than you should have」)
}
catch WeekendError.WorkAllWeekend
{
print(「You worked 48 hours :-0「)
}
catch
{
print(「Gulping the weekend exception」)
}複製代碼
false:Swift 中用於表示邏輯類型 — 布爾類型的兩個值之一,表明非真。
let alwaysFalse = false
let alwaysTrue = true
if alwaysFalse { print("Won't print, alwaysFalse is false 😉")}複製代碼
is:類型檢查運算符,用來識別一個實例是不是特定的類型。
class Person {}
class Programmer : Person {}
class Nurse : Person {}
let people = [Programmer(), Nurse()]
for aPerson in people
{
if aPerson is Programmer
{
print("This person is a dev")
}
else if aPerson is Nurse
{
print("This person is a nurse")
}
}複製代碼
nil:表示 Swift 中任何類型的無狀態的值。和 Objective-C 的 nil 不一樣,它是一個指向不存在對象的指針。
class Person{}
struct Place{}
//Literally any Swift type or instance can be nil
var statelessPerson:Person? = nil
var statelessPlace:Place? = nil
var statelessInt:Int? = nil
var statelessString:String? = nil複製代碼
rethrows:代表僅當該函數的一個函數類型的參數拋出錯誤時,該函數才拋出錯誤。
func networkCall(onComplete:() throws -> Void) rethrows
{
do
{
try onComplete()
}
catch
{
throw SomeError.error
}
}複製代碼
super:公開的訪問父類屬性、方法或別名。
class Person
{
func printName()
{
print("Printing a name. ")
}
}
class Programmer : Person
{
override func printName()
{
super.printName()
print("Hello World!")
}
}
let aDev = Programmer()
aDev.printName() //"Printing a name. Hello World!"複製代碼
self:每一個類型實例的隱含屬性,它徹底等於實例自己。在區別函數參數名和屬性名時很是有用。
class Person {
func printSelf()
{
print("This is me: \(self)")
}
}
let aPerson = Person()
aPerson.printSelf() //"This is me: Person"複製代碼
Self:在協議裏,表明最終符合給定協議的類型。
protocol Printable
{
func printTypeTwice(otherMe:Self)
}
struct Foo : Printable
{
func printTypeTwice(otherMe: Foo)
{
print("I am me plus \(otherMe)")
}
}
let aFoo = Foo()
let anotherFoo = Foo()
aFoo.printTypeTwice(otherMe: anotherFoo) //I am me plus Foo()複製代碼
throw:從當前上下文直接拋出一個錯誤。
enum WeekendError: Error
{
case Overtime
case WorkAllWeekend
}
func workOvertime () throws
{
throw WeekendError.Overtime
}複製代碼
throws:表示一個函數、方法或初始化方法可能會拋出一個錯誤。
enum WeekendError: Error
{
case Overtime
case WorkAllWeekend
}
func workOvertime () throws
{
throw WeekendError.Overtime
}
//"throws" indicates in the function's signature that I need use try, try? or try!
try workOvertime()複製代碼
true:Swift 中用於表示邏輯類型 — 布爾類型的兩個值之一,表明真。
let alwaysFalse = false
let alwaysTrue = true
if alwaysTrue { print("Always prints")}複製代碼
try:表示接下來的函數可能會拋出一個錯誤。有三種不一樣的用法:try、try? 和 try!。
let aResult = try dangerousFunction() //Handle it, or propagate it
let aResult = try! dangerousFunction() //This could trap
if let aResult = try? dangerousFunction() //Unwrap the optional複製代碼
_:通配符,匹配並忽略任何值。
for _ in 0..<3
{
print("Just loop 3 times, index has no meaning")
}複製代碼
another use
let _ = Singleton() //Ignore value or unused variable複製代碼
#available:if
、while
和 guard
語句的條件,根據特定的平臺,來在運行時查詢 API 的可用性。
if #available(iOS 10, *)
{
print("iOS 10 APIs are available")
}複製代碼
#colorLiteral:playground 字面量,返回一個可交互的顏色選擇器來賦值給一個變量。
let aColor = #colorLiteral //Brings up color picker複製代碼
#column:特殊的文字表達式,返回它開始位置的列數。
class Person {
func printInfo()
{
print("Some person info - on column \(#column)")
}
}
let aPerson = Person()
aPerson.printInfo() //Some person info - on column 53複製代碼
#else:編譯條件控制語句,容許程序條件編譯一些指定的代碼。與 #if
語句結合使用,當條件爲真時執行代碼的一部分,當相同的條件爲假時執行另外一部分。
#if os(iOS)
print("Compiled for an iOS device")
#else
print("Not on an iOS device")
#endif複製代碼
#elseif:條件編譯控制語句,容許程序條件編譯一些指定的代碼。與 #if
語句結合使用,在給出的條件爲真時,執行這部分的代碼。
#if os(iOS)
print("Compiled for an iOS device")
#elseif os(macOS)
print("Compiled on a mac computer")
#endif複製代碼
#endif:條件編譯控制語句,容許程序條件編譯一些指定的代碼。用於標記結束須要條件編譯的代碼。
#if os(iOS)
print("Compiled for an iOS device")
#endif複製代碼
#file:特殊的文字表達式,返回這個文件的名稱。
class Person {
func printInfo()
{
print("Some person info - inside file \(#file)")
}
}
let aPerson = Person()
aPerson.printInfo() //Some person info - inside file /*file path to the Playground file I wrote it in*/複製代碼
#fileReference:playground 字面量,返回一個選擇器來選擇文件,而後做爲一個 NSURL
實例返回。
let fontFilePath = #fileReference //Brings up file picker複製代碼
#function:特殊的文字表達式,用來返回一個函數的名稱,若是在方法裏,它返回方法名,若是在屬性的 getter 或者 setter 裏,它返回屬性的名稱,若是在特殊的成員,好比 init
或者 subscript
裏,它返回關鍵字,若是在文件的頂部,那它返回當前模塊的名稱。
class Person {
func printInfo()
{
print("Some person info - inside function \(#function)")
}
}
let aPerson = Person()
aPerson.printInfo() //Some person info - inside function printInfo()複製代碼
#if:條件編譯控制語句,容許程序條件編譯一些指定的代碼。根據一個或多個條件來判斷是否執行代碼。
#if os(iOS)
print("Compiled for an iOS device")
#endif複製代碼
#imageLiteral:playground 字面量,返回一個選擇器來選擇圖片,而後做爲一個 UIImage
實例返回。
let anImage = #imageLiteral //Brings up a picker to select an image inside the playground file複製代碼
#line:特殊的文字表達式,返回它所在位置的行數。
class Person {
func printInfo()
{
print("Some person info - on line number \(#line)")
}
}
let aPerson = Person()
aPerson.printInfo() //Some person info - on line number 5複製代碼
#selector:構成 Objective-C 選擇器的表達式,它使用靜態檢查來確保該方法存在,而且它也暴露給 Objective-C。
//Static checking occurs to make sure doAnObjCMethod exists
control.sendAction(#selector(doAnObjCMethod), to: target, forEvent: event)複製代碼
#sourceLocation:用於指定行數和文件名的行控制語句,該行數和文件名可能和正在編譯的源代碼的行數和文件名不一樣。適用於診斷和調試時,更改源代碼的位置。
#sourceLocation(file:"foo.swift", line:6)
//Reports new values
print(#file)
print(#line)
//This resets the source code location back to the default values numbering and filename
#sourceLocation()
print(#file)
print(#line)複製代碼
associativity:指定如何在沒有使用 left
、right
或 none
分組括號的狀況下,將具備相同優先級級別的運算符組合在一塊兒。
infix operator ~ { associativity right precedence 140 }
4 ~ 8複製代碼
convenience:類中的輔助初始化器,最終會把實例的初始化委託給特定的初始化器。
class Person {
var name:String
init(_ name:String)
{
self.name = name
}
convenience init()
{
self.init("No Name")
}
}
let me = Person()
print(me.name)//Prints "No Name"複製代碼
dynamic:表示對該成員或函數的訪問從未被編譯器內聯或虛擬化,這意味着對該成員的訪問始終使用 Objective-C 運行時來動態(而非靜態)派發。
class Person {
//Implicitly has the "objc" attribute now too
//This is helpful for interop with libs or
//Frameworks that rely on or are built
//Around Obj-C "magic" (i.e. some KVO/KVC/Swizzling)
dynamic var name:String?
}複製代碼
didSet:屬性觀察,在屬性存入一個值後當即調用。
var data = [1,2,3]
{
didSet
{
tableView.reloadData()
}
}複製代碼
final:阻止方法、屬性或者下標被繼承。
final class Person {}
class Programmer : Person {} //Compile time error複製代碼
get:返回成員給定的值。也用於計算屬性,能夠間接地獲取其餘屬性和值。
class Person {
var name:String
{
get { return self.name }
set { self.name = newValue}
}
var indirectSetName:String
{
get
{
if let aFullTitle = self.fullTitle
{
return aFullTitle
}
return ""
}
set (newTitle)
{
//If newTitle was absent, newValue could be used
self.fullTitle = "\(self.name) :\(newTitle)"
}
}
}複製代碼
infix:用於兩個目標之間的特定運算符。若是一個新的全局運算符被定義爲中置運算符,那它還須要成員之間的優先級組。
let twoIntsAdded = 2 + 3複製代碼
indirect:表示枚舉將另外一個枚舉的實例做爲一個或多個枚舉的關聯值。
indirect enum Entertainment
{
case eventType(String)
case oneEvent(Entertainment)
case twoEvents(Entertainment, Entertainment)
}
let dinner = Entertainment.eventType("Dinner")
let movie = Entertainment.eventType("Movie")
let dateNight = Entertainment.twoEvents(dinner, movie)複製代碼
lazy:屬性的初始值在第一次使用時再計算。
class Person {
lazy var personalityTraits = {
//Some crazy expensive database hit
return ["Nice", "Funny"]
}()
}
let aPerson = Person()
aPerson.personalityTraits //Database hit only happens now once it's accessed for the first time複製代碼
left:指定操做符的關聯順序爲從左到右,這樣在沒有分組括號的狀況下,相同優先級的也會被正確的分到一組。
//The "-" operator's associativity is left to right
10-2-4 //Logically grouped as (10-2) - 4複製代碼
mutating:容許在特定的方法中,對結構體或枚舉的屬性進行修改。
struct Person
{
var job = ""
mutating func assignJob(newJob:String)
{
self = Person(job: newJob)
}
}
var aPerson = Person()
aPerson.job //""
aPerson.assignJob(newJob: "iOS Engineer at Buffer")
aPerson.job //iOS Engineer at Buffer複製代碼
none:運算符沒有提供任何關聯性,這限制了相同優先級運算符的出現間隔。
//The "<" operator is a nonassociative operator
1 < 2 < 3 //Won't compile複製代碼
nonmutating:指定成員的 setter 不會修改它包含的實例,可是能夠有其餘的目的。
enum Paygrade
{
case Junior, Middle, Senior, Master
var experiencePay:String?
{
get
{
database.payForGrade(String(describing:self))
}
nonmutating set
{
if let newPay = newValue
{
database.editPayForGrade(String(describing:self), newSalary:newPay)
}
}
}
}
let currentPay = Paygrade.Middle
//Updates Middle range pay to 45k, but doesn't mutate experiencePay
currentPay.experiencePay = "$45,000"複製代碼
optional:用於描述協議中的可選方法。這些方法沒必要由符合協議的類型來實現。
@objc protocol Foo
{
func requiredFunction()
@objc optional func optionalFunction()
}
class Person : Foo
{
func requiredFunction()
{
print("Conformance is now valid")
}
}複製代碼
override:表示子類將提供本身的實例方法、類方法、實例屬性,類屬性或下標的自定義實現,不然它將從父類繼承。
class Person
{
func printInfo()
{
print("I'm just a person!")
}
}
class Programmer : Person
{
override func printInfo()
{
print("I'm a person who is a dev!")
}
}
let aPerson = Person()
let aDev = Programmer()
aPerson.printInfo() //I'm just a person!
aDev.printInfo() //I'm a person who is a dev!複製代碼
postfix:指定操做符在它操做的目標以後。
var optionalStr:String? = "Optional"
print(optionalStr!)複製代碼
precedence:表示一個操做符的優先級高於其餘,因此這些運行符先被應用。
infix operator ~ { associativity right precedence 140 }
4 ~ 8複製代碼
prefix:指定操做符在它的操做的目標以前。
var anInt = 2
anInt = -anInt //anInt now equals -2複製代碼
required:強制編譯器確保每一個子類都必須實現給定的初始化器。
class Person
{
var name:String?
required init(_ name:String)
{
self.name = name
}
}
class Programmer : Person
{
//Excluding this init(name:String) would be a compiler error
required init(_ name: String)
{
super.init(name)
}
}複製代碼
right:指定操做符的關聯順序爲從右到左,這樣在沒有分組括號的狀況下,相同優先級的也會被正確的分到一組。
//The "??" operator's associativity is right to left
var box:Int?
var sol:Int? = 2
let foo:Int = box ?? sol ?? 0 //Foo equals 2複製代碼
set:獲取成員的值來做爲它的新值。也可用於計算屬性,間接地設置其餘屬性和值。若是一個計算屬性的 setter 沒有定義一個名字來表明要設置的新值,那麼默認新值的名字爲 newValue
。
class Person {
var name:String
{
get { return self.name }
set { self.name = newValue}
}
var indirectSetName:String
{
get
{
if let aFullTitle = self.fullTitle
{
return aFullTitle
}
return ""
}
set (newTitle)
{
//If newTitle was absent, newValue could be used
self.fullTitle = "\(self.name) :\(newTitle)"
}
}
}複製代碼
Type:代指任何類型的類型,包括類的類型、結構體的類型、枚舉類型和協議類型。
class Person {}
class Programmer : Person {}
let aDev:Programmer.Type = Programmer.self複製代碼
unowned:在循環引用中,一個實例引用另外一個實例,在另外一個實例具備相同的生命週期或更長的生命週期時,不會對它強持有。
class Person {
var occupation:Job?
}
//Here, a job never exists without a Person instance, and thus never outlives the Person who holds it.
class Job {
unowned let employee:Person
init(with employee:Person)
{
self.employee = employee
}
}複製代碼
weak:在循環引用中,一個實例引用另外一個實例,在另外一個實例具備較短生命週期時,不會對它強持有。
class Person {
var residence:House?
}
class House {
weak var occupant:Person?
}
var me:Person? = Person()
var myHome:House? = House()
me!.residence = myHome
myHome!.occupant = me
me = nil
myHome!.occupant //Is now nil複製代碼
willSet:屬性觀察,在屬性即將存入一個值以前調用。
class Person {
var name:String?
{
willSet(newValue) {print("I've got a new name, it's \(newValue)!")}
}
}
let aPerson = Person()
aPerson.name = "Jordan" //Prints out "I've got a new name, it's Jordan!" right before name is assigned to複製代碼
呼!
這是一個有趣的創做。我選了一些我之前沒有真正仔細思考的東西寫,可是我認爲這些技巧是不須要像要考試的列表同樣記住的。
更好的是,隨時帶着這個列表。讓它隨時的刺激着你的腦波,這樣在你須要使用一些特定的關鍵字的時候,你就會知道它,而後使用它。
下次再見 — 感謝閱讀 ✌️。