//默认初始化方法 class Teacher { var name:String = "xiaoming"; } class Human { var name :String?; } class Personal { var name :String! } let teacher = Teacher(); print(teacher); let human = Human(); print(human); let personal = Personal(); print(personal);
//便利初始化方法 class Rect{ var width :Int; var height :Int; init(Int, height:Int){ self.width = width; self.height = height; } convenience init(width w:Int, h:Int){ self.init( w, height: h); } convenience init(w:Int, h:Int){ self.init( w, height: h); } func getArea() -> Int { return self.width * height; } } var rect = Rect(w: 10, h:20); print(rect.getArea()); rect = Rect( 20, height: 20); print(rect.getArea()); rect = Rect( 20, h:30); print(rect.getArea());
//使用闭包来设置默认值的初始化方法 class Student { var score:[Int] = { var scores:[Int] = Array(); for m in 0...3{ scores.append(m); } return scores; }() } print(Student().score);