一、初始化的两种方式javascript
1)这种方式有参数,在每次声明新的实例的时候,你能够在定义的同时给它的temperature赋一个不一样的值。java
struct Fahrenheit {
var temperature: Double
init(temperature: Double) {
self.temperature = temperature
}
}
var f = Fahrenheit(temperature: 20)
print("The default temperature is \(f.temperature)° Fahrenheit")复制代码
2)该方式每一个生成的实例的temperature都有一个默认值。git
struct Fahrenheit {
var temperature = 32.0
}复制代码
二、带有参数的构造器,调用的时候必须带有参数列表。github
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)
//该句会报错
let veryGreen = Color(0.0, 1.0, 0.0)复制代码
三、你能够用_
代替参数名swift
struct Celsius {
var temperatureInCelsius: Double
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
let gelsius = Celsius(30)
print(gelsius.temperatureInCelsius)复制代码
四、你能够将在构造期间值不肯定的属性声明为optional闭包
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."复制代码
五、构造器代理app
1)值类型(struct,enumeration)相对简单,它们不支持继承,只能调用本身的相关的构造器。函数
2)类的比较复杂,它们支持继承。ui
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 basicRect = Rect()
let originRect = Rect(origin: Point(x: 2.0, y: 2.0),size: Size(width: 5.0, height: 5.0))
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),size: Size(width: 3.0, height: 3.0))复制代码
六、Swift提供类的两种构造器,指定构造器(designated initializers)和便利构造器(convenience initializers)
咱们首要的应该使用designated initializers,每一个类应至少有一个designated initializers,若是没有必要的话,你能够不写convenience initializers。
1)声明designated initializers的语法spa
init(`parameters`) {
`statements`
}复制代码
2)声明convenience initializers的语法
convenience init(`parameters`) {
`statements`
}复制代码
例子:
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"
let mysteryMeat = Food()
// mysteryMeat's name is "[Unnamed]"复制代码
七、可失败的构造器(Failable Initializer)
可失败的构造器的关键字为init?
struct Animal {
let species: String
init?(species: String) {
if species.isEmpty { return nil }
self.species = species
}
}
let someCreature = Animal(species: "Giraffe")
// someCreature is of type Animal?, not Animal
if let giraffe = someCreature {
print("An animal was initialized with a species of \(giraffe.species)")
}
// Prints "An animal was initialized with a species of Giraffe"
//当你传递一个空字符创的时候,它会直接返回nil
let anonymousCreature = Animal(species: "")
// anonymousCreature is of type Animal?, not Animal
if anonymousCreature == nil {
print("The anonymous creature could not be initialized")
}
// Prints "The anonymous creature could not be initialized"复制代码
八、当你在init前面添加require关键字时,意味着该init方法必须在子类中实现。
class SomeClass {
required init() {
// initializer implementation goes here
}
}
class SomeSubclass: SomeClass {
required init() {
// subclass implementation of the required initializer goes here
}
}复制代码
九、使用闭包或者函数设置默认的属性值
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))
// Prints "true"
print(board.squareIsBlackAt(row: 7, column: 7))
// Prints "false"复制代码
Tips: