Swift 初始化Initialization

前端之家收集整理的这篇文章主要介绍了Swift 初始化Initialization前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在Swift中初始化,可以是对一个类,结构体或是枚举.不像OC那样,Swift的初始化没有返回值.

初始化的基本表达式:

init() {
    // perform some initialization here
}

1.结构体的初始化

struct Fahrenheit {
    var temperature: Double
    init() {
        temperature = 32.0
    }
}
var f = Fahrenheit()
print("The default temperature is \(f.temperature)° Fahrenheit")
// Prints "The default temperature is 32.0° Fahrenheit"
上面的初始化实在init方法里面给属性temperature设置的初始值32.0.

也可以不在init里面设置初始值:

struct Fahrenheit {
    var temperature = 32.0
<p>}</p>

2.自定义初始化

truct Celsius {
    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)
// boilingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0
上面的初始化定义了,华氏温度和摄氏温度的转换公式.

3.利用外部参数来给属性设置值

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)

4.不使用外部参数名

struct Celsius {
    var temperatureInCelsius: Double
    init(fromFahrenheit fahrenheit: Double) {
        temperatureInCelsius = (fahrenheit - 32.0) / 1.8
    }
    init(fromKelvin kelvin: Double) {
        temperatureInCelsius = kelvin - 273.15
    }
    init(<span style="color:#cc0000;">_</span> celsius: Double) {
        temperatureInCelsius = celsius
    }
}
let bodyTemperature = Celsius(37.0)
// bodyTemperature.temperatureInCelsius is 37.0
上面是通过写一个下划线" _"来代替明确的外部参数名.

5.可选属性类型/初始化的时候指定常亮属性

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()
// Prints "Do you like cheese?"
cheeseQuestion.response = "Yes,I do like cheese."

6.默认值初始化/缺省值

class ShoppingListItem {
    var name: String?
    var quantity = 1
    var purchased = false
}
var item = ShoppingListItem()
这个类中,我们设置了quantity初始的默认值 = 1.

7.逐个成员的初始化

下面看看Rect的初始化过程.

先初始化size和point

struct Size {
    var width = 0.0,height = 0.0
}
struct Point {
    var x = 0.0,y = 0.0
}
再初始化Rect
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 originRect = Rect(origin: Point(x: 2.0,y: 2.0),size: Size(width: 5.0,height: 5.0))
// originRect's origin is (2.0,2.0) and its size is (5.0,5.0)

let centerRect = Rect(center: Point(x: 4.0,y: 4.0),size: Size(width: 3.0,height: 3.0))
// centerRect's origin is (2.5,2.5) and its size is (3.0,3.0)

8.类继承和初始化

在这里提到了两个构造器,指定构造器和方便构造器,没看懂.上截图吧

从这两张图中,我们似乎也可以看出什么来.D-->D,C-->D/C.

这个部分感觉这个东西最好玩Unnamed

class Food {
    var name: String
    init(name: String) {
        self.name = name
    }
    convenience init() {
        self.init(name: "[Unnamed]")
    }
}
这个类的初始化
let namedMeat = Food(name: "Bacon")
// namedMeat's name is "Bacon"
看,这里就显示Unnamed的作用可,可以自定把对象的名字获取.

方便构造器的初始化有个关键字:convenience.

下面这类,继承自Food

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)
    }
}
它的初始化过程:


有继承有C也有D了.

9.枚举的初始化

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.")
}
// Prints "This is not a defined temperature unit,so initialization Failed."

10.枚举带初始值的初始化

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."
原文链接:/swift/324271.html

猜你在找的Swift相关文章