//定义一个简单的枚举类
enum Skin{
case White
case Black
case Yellow
}
//定义一个student类
class Student{
var name = "张三"
var age = 26
var skin:Skin = .Yellow
}
//可以在其他类实例化对象
let student = Student()
print(student.name)
print(student.age)
print(student.skin)
//打印结果为 张三 26 yellow
添加构造器
enum Skin{
case White
case Black
case Yellow
}
//定义一个student类
class Student{
var name = "张三"
var age = 26
var skin:Skin = .Yellow
//使用self来区分是否是全局的变量
init(name:String,age:Int,skin:Skin) {
self.name = name
self.age = age
self.skin = skin
}
}
//实力化
let student = Student(name: "小米", age: 26, skin: .White)
print(student.name)
print(student.age)
print(student.skin)
//打印结果为 小米 26 white
便利构造器
enum Skin{
case Black
case White
case Yellow
}
class Student{
var name = "张三"
var age = 26
var skin:Skin = .Yellow
init(name:String,age:Int,skin:Skin) {
self.name = name
self.age = age
self.skin = skin
}
//
//便利构造器
convenience init(age:Int) {
self.init(name: "小米", age: age, skin: .White)
}
}
// 初始化的时候会有两种选择 一种是构造器中的三个参数全部更改,一种是构造器中只改变年龄
let student = Student(age:100)
print(student.name)
print(student.age)
print(student.skin)
//打印结果为 小米 100 white
网友评论