Swift4 基础部分: Initialization

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

系列文章:

  • Swift4 基础部分:The Basics
  • Swift4 基础部分:Basic Operators
  • Swift4 基础部分:Strings and Characters
  • Swift4 基础部分:Collection Types
  • Swift4 基础部分:Control Flow
  • Swift4 基础部分:Functions
  • Swift4 基础部分:Closures
  • Swift4 基础部分: Enumerations
  • Swift4 基础部分: Classes and Structures
  • Swift4 基础部分: Properties
  • Swift4 基础部分: Methods
  • Swift4 基础部分: Subscripts
  • Swift4 基础部分: Inheritance

初始化器(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

你可能感兴趣的:(Swift4 基础部分: Initialization)