class Student: NSObject {
var name = ""
//实例方法的某个参数名称与实例属性名称相同的时,参数名称优先,这时需要用self来区分参数名称和属性名称
func sayHI(name :String) {
print("hello \(name),I am \(self.name)")
}
func eat(food:String) {
print("eat \(food)")
}
}
let student = Student()
student.name = "hanmeimei"
student.sayHI(name: "lilei") //hello lilei,I am hanmeimei
student.eat(food: "apple") //eat apple
mutating
关键字,从而允许修改属性)struct Teacher {
var name = "lilei"
var age = 0
mutating func changeName() {
name = "hanmeimei"
}
}
var teacher = Teacher()
print(teacher.name) //lilei
teacher.changeName()
print(teacher.name) //hanmeimei
mutating
关键字,从而允许修改属性)enum Color{
case red
case yellow
case green
mutating func changeColor() {
switch self {
case .red:
self = .yellow
case .yellow:
self = .green
case .green:
self = .red
}
}
}
var color = Color.red
print(color) //red
color.changeColor()
print(color) //yellow
class Student: NSObject {
static var name = "hanmeimei"
class func sayHI(name :String) {
print("hello \(name),I am \(self.name)")
}
}
Student.sayHI(name: "lilei") //hello lilei,I am hanmeimei
struct Teacher {
static var name = "lilei"
static func changeName() {
name = "hanmeimei"
}
}
print(Teacher.name) //lilei
Teacher.changeName()
print(Teacher.name) //hanmeimei