Methods

Instance Methods 对象方法

class Counter {
    var count = 0
    func increment() {
        count++
    }
    func incrementBy(amount: Int) {
        count += amount
    }
    func reset() {
        count = 0
    }
}

let counter = Counter()
counter.increment()
counter.incrementBy(3)
counter.reset()

Local and External Parameter Names for Methods 方法的本地和外部参数名

swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter news by default. swift将对象方法的第一个参数看做只有本地参数名,而第二个以及随后的参数都将拥有外部和本地参数名

Modifying External Parameter Name Behavior for Methods

显示的写出#可以让对象方法第一个参数也拥有外部参数名,在第二个及随后的参数名前加下划线_取消参数的外部参数名

The self Property

Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. 每一个对象都有一个隐式参数self用来指代对象自己

struct Point {
    var x = 0.0, y = 0.0
    func isToTheRightOfX(x: Double) -> Bool {
        return self.x > x
    }
}

Modifying Value Types from Within Instance Methods

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods. 结构和枚举(注意这里没有类)是值类型,默认情况下,值类型的属性的值是不能被对象方法更改的。

You can opt in to this behavior by placing the mutating keyword before the fun keyword for that method. 你可以通过在fun关键字前面加mutating来实现这项功能

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveByX(deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}

Note that you cannot call a mutating method on a constant of structure type, because its properties cannot be changed. 注意你不能调用一个mutating的方法来更改一个结构体的常量(区别于类,结构体是值类型)

let fixedPoint = Point(x: 3.0, y: 5.0)
fixedPoint.moveByX(2.0, y: 3.0)
// this will report an error

Assigning to self Within a Mutating Method

Mutating methods can assign an entirely new instance to the implicit self property. 好家伙,swift还可以再mutating方法里面直接把self给换了(这不就是谋权篡位吗,不知道他们怎么想的) 例如上面的Point结构体还可以这样写

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveByX(deltaX: Double, y deltaY: Double) {
        self = Point(x: x+deltaX, y: y+deltaY)
    }
}
Mutating methods for enumerations can set the implicit self parameter to be a different member from the same enumeration. 枚举类型的mutating方法可以把self设置成同样地枚举类型的不同成员

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()
Type Methods 类型方法

Instance methods are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. 对象方法是被一个特定类型的对象(实例)所调用的。你还可以定义一种被类型本身调用的方法。这类方法就被称作类型方法

A type method can call another type method with the other method's name, without needing to prefix it with the type name. 一个类型方法可以调用类型方法而不用写上类型名字的前缀

就像类型属性一样,要声明一个类型方法在structure和enumeration中在func前面加static,在class类型的func前面加class

// The example below defines a structure call LevelTracker, which tracks a player's progress
// through the different levels of stages of a game. It is a single-player game, but can store 
// information for multiple players on a single device.
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 func advanceToLevel(level: Int) -> Bool {
        if LevelTracker.levelIsUnlocked(level) {
            currentLevel = level
            return true
        } else { return false }
    }
}
上面例子中声明了一个LevelTracker类来跟踪一个player解锁的游戏等级,一开始解锁的只有一级,然后提供了可以改变currentLevel的mutating的方法advanceToLevel,与之配合的是下面的这个player类

// The LevelTacker structure is used with the Player class, 
// shown below to track and update the progress of an individual player
class Player {
    var tracker = LevelTracker()
    let playName: String
    func completedLevel(level: Int) {
        LevelTracker.unlockLevel(level+1)
        tracker.advanceToLevel(level+1)
    }
    init(name: String) {
        playName = name
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值