方法(Methods)

方法概念:

函数在类,结构体,枚举中就叫方法。

实例方法举例:

class Counter {
   var count = 0
  func increment() {
       count += 1
  }
  func incrementBy(amount: Int) {
      count += amount
}
func reset() {
       count = 0
}
}```
#####实例方法需要实例来调用如通过counter 实例调用Counter类中的increment,incrementBy,reset三个方法

let counter = Counter()
// the initial counter value is 0
counter.increment()
// the counter's value is now 1
counter.incrementBy(5)
// the counter's value is now 6
counter.reset()
// the counter's value is now 0```

Mutating关键字

Swift通过Mutating关键字修改实例方法中的值类型数据,例如在moveByX方法前面加上mutating 修改Point中的x和y的值
struct Point {
    var x = 0.0, y = 0.0
    mutating func moveByX(deltaX: Double, y deltaY: Double) {
    x += deltaX
    y += deltaY
   }
 }
 var somePoint = Point(x: 1.0, y: 1.0)
 somePoint.moveByX(2.0, y: 3.0)
 print("The point is now at (\(somePoint.x), \(somePoint.y))")
 // Prints "The point is now at (3.0, 4.0)"```
####类型方法
#####类型方法有两种关键字:static和class,class关键字表示该方法在子类中可以重写覆盖。在swift中类、结构体、枚举都有类型方法。

class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()```

类型方法只能访问静态变量(在该变量前也有static关键字修饰的变量)实例方法前面加上mutating 关键字以后可以访问静态变量和实例变量
struct LevelTracker {
      static var highestUnlockedLevel = 1
      static func unlockLevel(level: Int) {
      if level > highestUnlockedLevel { highestUnlockedLevel = level }
 }
      static func levelIsUnlocked(level: Int) -> Bool {
          return level <= highestUnlockedLevel
     }
      var currentLevel = 1
      //mutating 关键字访问实例变量
       mutating func advanceToLevel(level: Int) -> Bool {
            if LevelTracker.levelIsUnlocked(level) {
                       currentLevel = level
                       return true
              } else {
                      return false
         }
     }
 }```
####init方法
#####通过init初始化类中的变量

class Player {
let playerName: String
init(name: String) {
playerName = name
}
}
var player = Player(name: "Argyrios")
Print(player.playerName)```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young阅读 4,225评论 1 10
  • 翻译:pp-prog 校对:zqp 本页包含内容: 实例方法(Instance Methods 类型方法(Typ...
    bill阅读 832评论 1 3
  • 132.转换错误成可选值 通过转换错误成一个可选值,你可以使用 try? 来处理错误。当执行try?表达式时,如果...
    无沣阅读 1,498评论 0 3
  • 方法是与某些特定类型相关联的函数。类、结构体、枚举都可以定义实例方法;实例方法为特定类型的实例封装具体的任务与功能...
    EndEvent阅读 661评论 3 5
  • 结构体和枚举能够定义方法是 Swift 与 C/Objective-C 的主要区别之一。在 Objective-C...
    飞行的猫阅读 380评论 0 0

友情链接更多精彩内容