美文网首页
Swift-方法

Swift-方法

作者: 邢罗康 | 来源:发表于2023-04-19 02:15 被阅读0次

【返回目录】


  • 枚举、结构体、类都可以定义实例方法(Instance Method)、类型方法(Type Method)
    1.实例方法通过实例调用
    2.类型方法通过类型调用,用static或者class关键字定义
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、let
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)







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


相关文章

  • Swift-方法

    在Swift中,类,结构体,枚举,都能定义实例方法。 结构和枚举可以在Swift中定义方法的事实是与C和Objec...

  • swift-类属性

    了解属性之前,需要先了解前面的swift-类结构内容 - swift-类结构源码探寻[https://www.ji...

  • Swift-自定义UITableViewCell和View(XI

    Swift-自定义UITableViewCell和View 概要 本文主要粗略的整理两种方法用于自定义UITabl...

  • Swift4.0 --- 第一节:变量和常量

    // // ViewControllerOne.swift // Swift-(1) // // Created ...

  • Swift4.0 --- 可选项

    // // ViewControllerTwo.swift // Swift-(1) // // Created ...

  • Swift4.0 --- 可选项的判断

    // // ViewControllerFour.swift // Swift-(1) // // Created...

  • Swift4.0 --- 逻辑分支

    // // ViewControllerThree.swift // Swift-(1) // // Create...

  • Swift-类型方法

    类型方法 实例方法是被某个类型的实例调用的方法。你也可以定义在类型本身上调用的方法,这种方法就叫做类型方法。在方法...

  • Swift-实例方法

    方法是与某些特定类型相关联的函数。类、结构体、枚举都可以定义实例方法;实例方法为给定类型的实例封装了具体的任务与功...

  • swift-方法一

网友评论

      本文标题:Swift-方法

      本文链接:https://www.haomeiwen.com/subject/glmkjdtx.html