swift 方法(实例方法、类方法)

2023-11-22 09:11:32 浏览数 (2)

实例方法

代码语言:javascript复制
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关键字,从而允许修改属性)
代码语言:javascript复制
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关键字,从而允许修改属性)
代码语言:javascript复制
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

类方法

代码语言:javascript复制
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
  • 结构体
代码语言:javascript复制
struct Teacher {
    static var name = "lilei"
    static func changeName() {
        name = "hanmeimei"
    }
}

print(Teacher.name)     //lilei
Teacher.changeName()
print(Teacher.name)     //hanmeimei

0 人点赞