Swift语言之对象实例化
在众多流行的面向对象的编程语言里,实例化一般调用实例构造器,当然某些情况下也会通过反射来实现实例化操作;在Swift中,我们要初始化一个对象实例的时候会有很多选择,例如下面有一个名为People的类,其仅包含了一个实例化构造器:
class People: Printable { let name: String let age: Int required init(name:String, age:Int){ self.name = name self.age = age } var description: String { return "My name is \(name) and my age is \(age)" } }
最简单实例化操作:
var nick = People(name: "Nick", age: 30)
通过类型别名来实现一个变形:
typealias PeopleType = People var nick = PeopleType(name: "Nick", age: 30)
如果能得到People的MetaType,我们还可以这样做:
var peopleType: People.Type = People.self var nick: People = peopleType(name: "Nick", age: 30)
当然我们也可以直接调用People.self的init方法来初始化实例:
var nick: People = People.self.init(name: "Nick", age: 30)
在这种情况下,我们可以省略掉self,直接在People上调用init方法就可以了:
var nick: People = People.init(name: "Nick", age: 30)