Swift4 基础部分: Initialization

本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

系列文章:

初始化器(Initializers)

  • 直接查看基本的使用例子:

例子:

struct Fahrenheit{
    var temperature:Double;
    init() {
        temperature = 32.0;
    }
}

var f = Fahrenheit();
print("The default temperature is \(f.temperature)° Fahrenheit")

执行结果:

The default temperature is 32.0° Fahrenheit

自定义初始化(Customizing Initialization)

例子:

    var temperatureInCelsius:Double;
    init(fromFahrenheit fahrenheit: Double) {
        temperatureInCelsius = (fahrenheit - 32.0) / 1.8
    }
    init(fromKelvin kelvin: Double) {
        temperatureInCelsius = kelvin - 273.15
    }
}

let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
print("The default temperature is \(boilingPointOfWater.temperatureInCelsius)° Fahrenheit")
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
print("The default temperature is \(freezingPointOfWater.temperatureInCelsius)° Fahrenheit")

执行结果:

The default temperature is 100.0° Fahrenheit
The default temperature is 0.0° Fahrenheit

参数名称和参数标签(Parameter Names and Argument Labels)

例子:

struct Color {
    let red,green,blue: Double;
    init(red:Double,green:Double,blue:Double){
        self.red = red;
        self.green = green;
        self.blue = blue;
    }
    
    init(white:Double){
        red = white;
        green = white;
        blue = white;
    }
}

let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)
let halfGray = Color(white: 0.5)
print("magenta red:\(magenta.red) green:\(magenta.green) blue:\(magenta.blue)");
print("halfGray red:\(halfGray.red) green:\(halfGray.green) blue:\(halfGray.blue)");

执行结果:

magenta red:1.0 green:0.0 blue:1.0
halfGray red:0.5 green:0.5 blue:0.5

不需要参数标签的初始化器(Initializer Parameters Without Argument Labels)

直接看例子:

struct Celsius{
    var temperatureInCelsius:Double;
    init(fromFahrenheit fahrenheit:Double){
        temperatureInCelsius = (fahrenheit - 32.0) / 1.8;
    }
    
    init(fromKelvin kelvin:Double){
        temperatureInCelsius = kelvin - 273.15;
    }
    
    // 此处就是具体的体现
    init(_ celsius:Double){
        temperatureInCelsius = celsius;
    }
}
let bodyTemperature = Celsius(37.0);
print(bodyTemperature.temperatureInCelsius);

执行结果:

37.0

可选属性类型(Optional Property Types)

If your custom type has a stored property that is 
logically allowed to have “no value”—perhaps because its 
value cannot be set during initialization, or because it 
is allowed to have “no value” at some later point—declare 
the property with an optional type. 
  • 如果你定制的类型是允许取值为空的存储型属性--不管是因为它无法在初始化时赋值,还是因为它可以在之后某个时间点可以赋值为空--你都需要将它定义为可选类型。
class SurveyQuestion {
    var text: String;
    var response: String?;
    
    init(text: String) {
        self.text = text
    }
    
    func ask() {
        print(text)
    }
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
cheeseQuestion.response = "Yes, I do like cheese."

执行结果:

Do you like cheese?

构造过程中常量属性的修改(Assigning Constant Properties During Initialization)

  • 只要在构造过程结束前常量的值能确定,你可以在构造过程中的任意时间点修改常量属性的值。
  • 对某个类实例来说,它的常量属性只能在定义它的类的构造过程中修改;不能在子类中修改。

例子:

class SurveyQuestion {
    let text: String
    var response: String?
    init(text: String) {
        self.text = text
    }
    func ask() {
        print(text)
    }
}

class DetailSurveyQuestion:SurveyQuestion{
    
    init(content content: String){
        self.text = content;
    }
}
let beetsQuestion = SurveyQuestion(text: "How about beets?")
beetsQuestion.ask()
// 输出 "How about beets?"
beetsQuestion.response = "I also like beets. (But not with cheese.)"

执行结果:编译错误验证上述结论2

Playground execution failed: error: MyPlayground.playground:900:19: error: cannot assign to property: 'text' is a 'let' constant
        self.text = content;
        ~~~~~~~~~ ^

去掉子类的实现,执行结果:

How about beets?

默认构造器(Default Initializers)

Swift provides a default initializer for any structure or 
class that provides default values for all of its 
properties and does not provide at least one initializer 
itself.
  • Swift 将为所有属性已提供默认值的且自身没有定义任何构造器的结构体或基类,提供一个默认的构造器。

例子:


class ShoppingListItem {
    var name: String?;
    var quantity = 1;
    var purchased = false;
}
var item = ShoppingListItem();

结构体的逐一成员构造器(Memberwise Initializers for Structure Types)

Structure types automatically receive a memberwise 
initializer if they do not define any of their own custom 
initializers. Unlike a default initializer, the structure 
receives a memberwise initializer even if it has stored 
properties that do not have default values.
  • 结构体类型可以自动接收逐一成员构造器,如果他们没有定义任何的构造器。

例子:

struct Size {
    var width = 0.0, height = 0.0;
}
let size = Size(width:2.0, height:2.0);
print("size \(size.width) \(size.height)");

执行结果:

size 2.0 2.0

值类型的构造器代理(Initializer Delegation for Value Types)

Initializers can call other initializers to perform part 
of an instance’s initialization. This process, known as 
initializer delegation, avoids duplicating code across 
multiple initializers. 
  • 构造器可以通过调用其它构造器来完成实例的部分构造过程。这一过程称为构造器代理,它能避免多个构造器间的代码重复。

例子:

struct Size {
    var width = 0.0, height = 0.0;
}

struct Point {
    var x = 0.0, y = 0.0;
}

struct Rect {
    var origin = Point();
    var size = Size();
    init(){}
    init(origin:Point, size:Size){
        self.origin = origin;
        self.size = size;
    }
    
    init(center:Point, size:Size){
        let originX = center.x - (size.width / 2);
        let originY = center.y - (size.height / 2);
        self.init(origin: Point(x:originX,y:originY), size: size);
    }
}

let originReact = Rect(origin:Point(x:2.0,y:2.0),size:Size(width:5.0,height:5.0));
print("point:\(originReact.origin) size:\(originReact.size)");

执行结果:

point:Point(x: 2.0, y: 2.0) size:Size(width: 5.0, height: 5.0)

类的继承与构造过程(Class Inheritance and Initialization)

Swift defines two kinds of initializers for class types to 
help ensure all stored properties receive an initial 
value. These are known as designated initializers and 
convenience initializers.
  • Swift 提供了两种类型的类构造器来确保所有类实例中存储型属性都能获得初始值,它们分别是指定构造器和便利构造器。

指定构造器和便利构造器的语法(Syntax for Designated and Convenience Initializers)

指定构造器语法:

init(parameters) {
    statements
}

便利构造器语法:

convenience init(parameters) {
    statements
} 

类的构造器代理(Initializer Delegation for Class Types)

基本规则:

Designated initializers must always delegate up.
Convenience initializers must always delegate across.
  • 指定构造器必须总是向上代理。
  • 便利构造器必须总是横向代理。

构造器的继承与重载(Initializer Inheritance and Overriding)

When you write a subclass initializer that matches a 
superclass designated initializer, you are effectively 
providing an override of that designated initializer. 
Therefore, you must write the override modifier before the 
subclass’s initializer definition.
  • 可以在子类中通过关键字override重载父类的构造器方法。

例子:

class Vehicle {
    var numberOfWheels = 0;
    var description:String {
        return "\(numberOfWheels) wheel(s)";
    }
}

class Bicycle:Vehicle {
    override init() {
        super.init();
        numberOfWheels = 2;
    }
}

let bicycle = Bicycle();
print("Bicycle: \(bicycle.description)");

执行结果:

Bicycle: 2 wheel(s)

指定构造器和便利构造器实战(Designated and Convenience Initializers in Action)

直接看一下指定构造器与便利构造器的实际应用的例子:

class Food {
    var name: String;
    
    init(name: String) {
        self.name = name;
    }
    
    convenience init() {
        self.init(name: "[Unnamed]");
    }
}

class RecipeIngredient: Food {
    var quantity: Int;
    
    init(name: String, quantity: Int) {
        self.quantity = quantity;
        super.init(name: name);
    }
    
    override convenience init(name: String) {
        self.init(name: name, quantity: 1);
    }
}

class ShoppingListItem: RecipeIngredient {
    var purchased = false;
    
    var description: String {
        var output = "\(quantity) x \(name)";
        output += purchased ? " ✔" : " ✘";
        return output;
    }
}

var breakfastList = [
    ShoppingListItem(),
    ShoppingListItem(name: "Bacon"),
    ShoppingListItem(name: "Eggs", quantity: 6),
];
breakfastList[0].name = "Orange juice";
breakfastList[0].purchased = true;
for item in breakfastList {
    print(item.description);
}

执行结果:

1 x Orange juice ✔
1 x Bacon ✘
6 x Eggs ✘

可失败的构造器(Failable Initializers)

It is sometimes useful to define a class, structure, or 
enumeration for which initialization can fail. This 
failure might be triggered by invalid initialization 
parameter values, the absence of a required external 
resource, or some other condition that prevents 
initialization from succeeding.
  • 如果一个类,结构体或枚举类型的对象,在构造自身的过程中有可能失败,则为其定义一个可失败构造器,是非常有用的。这类错误可能是参数或者确实外部资源等。

例子:

struct Animal {
    let species:String;
    init?(species: String){
        if species.isEmpty{
            return nil;
        }
        
        self.species = species;
    }
}

let someCreature = Animal(species: "Giraffe");
if let giraffe = someCreature {
    print("An animal was initialized with a species of \(giraffe.species)");
}

执行结果:

An animal was initialized with a species of Giraffe

枚举类型的可失败构造器(Failable Initializers for Enumerations)

例子:

enum TemperatureUnit {
    case kelvin, celsius, fahrenheit
    init?(symbol: Character) {
        switch symbol {
        case "K":
            self = .kelvin
        case "C":
            self = .celsius
        case "F":
            self = .fahrenheit
        default:
            return nil
        }
    }
}

let fahrenheitUnit = TemperatureUnit(symbol: "F")
if fahrenheitUnit != nil {
    print("This is a defined temperature unit, so initialization succeeded.")
}
// Prints "This is a defined temperature unit, so initialization succeeded."

let unknownUnit = TemperatureUnit(symbol: "X")
if unknownUnit == nil {
    print("This is not a defined temperature unit, so initialization failed.")
}

执行结果:

This is a defined temperature unit, so initialization succeeded.
This is not a defined temperature unit, so initialization failed.

带原始值的枚举类型的可失败构造器(Failable Initializers for Enumerations with Raw Values)

例子:

enum TemperatureUnit: Character {
    case kelvin = "K", celsius = "C", fahrenheit = "F"
}

let fahrenheitUnit = TemperatureUnit(rawValue: "F")
if fahrenheitUnit != nil {
    print("This is a defined temperature unit, so initialization succeeded.")
}

let unknownUnit = TemperatureUnit(rawValue: "X")
if unknownUnit == nil {
    print("This is not a defined temperature unit, so initialization failed.")
}

执行结果:

This is a defined temperature unit, so initialization succeeded.
This is not a defined temperature unit, so initialization failed.

构造失败的传递(Propagation of Initialization Failure)

A failable initializer of a class, structure, or 
enumeration can delegate across to another failable 
initializer from the same class, structure, or 
enumeration. Similarly, a subclass failable initializer 
can delegate up to a superclass failable initializer.
  • 可失败构造器在同一类,结构体和枚举中横向代理其他的可失败构造器。类似的,子类的可失败构造器也能向上代理基类的可失败构造器。

例子:

class Product {
    let name: String;
    init?(name: String) {
        if name.isEmpty { return nil; }
        self.name = name;
    }
}

class CartItem: Product {
    let quantity: Int;
    init?(name: String, quantity: Int) {
        if quantity < 1 { return nil; }
        self.quantity = quantity;
        super.init(name: name);
    }
}

if let twoSocks = CartItem(name: "sock", quantity: 2) {
    print("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)");
}

if let zeroShirts = CartItem(name: "shirt", quantity: 0) {
    print("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)");
} else {
    print("Unable to initialize zero shirts");
}

if let oneUnnamed = CartItem(name: "", quantity: 1) {
    print("Item: \(oneUnnamed.name), quantity: \(oneUnnamed.quantity)");
} else {
    print("Unable to initialize one unnamed product");
}

执行结果:

Item: sock, quantity: 2
Unable to initialize zero shirts
Unable to initialize one unnamed product

覆写父类的可失败的构造器(Overriding a Failable Initializer)

You can override a superclass failable initializer in a subclass, just like any other initializer.
  • 就如同其它构造器一样,你也可以用子类的可失败构造器覆盖基类的可失败构造器。

例子:

class Document {
    var name: String?;

    init() {};

    init?(name: String) {
        if name.isEmpty { return nil }
        self.name = name
    }
}

class AutomaticallyNamedDocument: Document {
    override init() {
        super.init();
        self.name = "[Untitled]";
    }
    override init(name: String) {
        super.init();
        if name.isEmpty {
            self.name = "[Untitled]";
        } else {
            self.name = name;
        }
    }
}

必须存在的构造器(Required Initializers)

Write the required modifier before the definition of a 
class initializer to indicate that every subclass of the 
class must implement that initializer: 

class SomeClass {
    required init() {
        // initializer implementation goes here
    }
}

class SomeSubclass: SomeClass {
    required init() {
        // subclass implementation of the required initializer goes here
    }
}

通过闭包和函数来设置属性的默认值(Setting a Default Property Value with a Closure or Function)

If a stored property’s default value requires some 
customization or setup, you can use a closure or global 
function to provide a customized default value for that 
property. 
  • 如果某个存储型属性的默认值需要特别的定制或准备,你就可以使用闭包或全局函数来为其属性提供定制的默认值。

例子:


struct Chessboard {
    let boardColors:[Bool] = {
        var temporaryBoard = [Bool]();
        var isBlack = false;
        for i in 1...8 {
            for j in 1...8 {
                temporaryBoard.append(isBlack);
                isBlack = !isBlack;
            }
        }
        isBlack = !isBlack;
        return temporaryBoard;
    }()
    
    func squareIsBlackAt(row:Int,column:Int) -> Bool{
        return boardColors[row * 8 + column];
    }
}

let board = Chessboard();
print(board.squareIsBlackAt(row: 0, column: 1));
print(board.squareIsBlackAt(row: 7, column: 7));

执行结果:

true
true
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容