Swift-方法

2023-04-19  本文已影响0人  邢罗康

【返回目录】


class Car {
    static var count = 0
    init() {
        Car.count += 1
    }
    static func getCount() -> Int {
        return count
    }
}
let c1 = Car()
let c2 = Car()
let c3 = Car()
print(Car.getCount()) // 3



self

self在实例方法中代表实例,在类型方法中代表类型。在类型方法static func getCount()中,cout等价于self.coutCar.self.coutCar.cout


mutating

结构体和枚举是值类型。默认情况下,值类型的属性不能在它的实例方法中被修改。
要使用可变方法,将关键字 mutating 放到方法的 func 关键字的前面。

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
        //等价
        //self = Point(x: 10.5, y: 20.0)
    }
}
enum TriStateSwitch {
    case off, low, high
    mutating func next() {
        switch self {
        case .off:
            self = .low
        case .low:
            self = .high
        case .high:
            self = .off
        }
    }
}
var ovenLight = TriStateSwitch.low
ovenLight.next()
// ovenLight 现在等于 .high
ovenLight.next()
// ovenLight 现在等于 .off



@discardableResult

在func前面加个@discardableResult修饰符,可以消除函数调用后返回值未使用的警告⚠️

struct Pointing {
    var x = 0.0, y = 0.0
    @discardableResult mutating func moveX(deltaX: Double) -> Double {
        x += deltaX
        return x
    }
}
var p = Pointing()
p.moveX(deltaX: 10)




将方法赋值给var、let

struct Person {
    var age: Int
    func run(_ v: Int) {
        print("func run ",age,v)
    }
    static func run(_ v: Int) {
        print("func run ",v)
    }
}

方法也可以想函数那样赋值给var、let

let p = Person(age: 10)
print(p.age)
p.run(20)
var fn = Person.run
var fn2 = fn(Person(age: 10))
fn2(20)

类方法和实例方法同时存在时:

let fn = Person.run
fn(20)
let fn: (Person) -> (Int) -> () = Person.run
fn(Person(age: 10))(20)







【上一篇】:属性
【下一篇】:下标


上一篇 下一篇

猜你喜欢

热点阅读