// 类 初始化时,属性如果没有默认值 ,必须加上构造器
class Dog {
var name:String
var age:Int
init(name:String,age:Int) {
self.name = name
self.age = age
}
}
let dog = Dog(name:"哈士奇",age:2)
print("\(dog.name)已经\(dog.age)岁了!")
//便利构造器,和默认给初始值一样的效果 关键字convenience
class Pig {
var name:String
var age:Int
init(name:String,age:Int) {
self.name = name
self.age = age
}
convenience init() {
self.init(name:"骚猪",age:3)
}
}
let pig = Pig()
print("\(pig.name)已经\(pig.age)岁了!")
//结构体的初始化 与 类 不同,可以不用给默认值,也不用写构造器,但是实例化的时候必须给值
struct Cat {
var name:String
var age:Int
}
// let cat = Cat() //这种写法会报错,
let cat = Cat(name:"猫",age:3)
print("\(cat.name)已经\(cat.age)岁了!")
//可失败构造器
struct Animal {
var name:String
init?(name:String) {
if name.isEmpty {
print("动物的名字为空")
return nil
}
self.name = name;
}
}
let animal = Animal(name:"11")
//可失败构造器 init 后面要加上? 否则会报错