# Swift 方法

network | | 访问(59)

### 实例方法

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

Counter类里定义了三个实例方法：

• increment 计数器增量加1

• incrementBy(amount: Int)计数器由特定的整数作为增量

• reset 重置计数器的值为0

```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```

### 方法的局部和外部参数名

```class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}```

```let counter = Counter()
counter.incrementBy(5, numberOfTimes: 3)
// counter value is now 15```

```func incrementBy(amount: Int, #numberOfTimes: Int) {
count += amount * numberOfTimes
}```

### self 属性

```func increment() {
self.count++
}```

```struct Point {
var x = 0.0, y = 0.0
func isToTheRightOfX(x: Double) -> Bool {
return self.x > x
}
}
let somePoint = Point(x: 4.0, y: 5.0)
if somePoint.isToTheRightOfX(1.0) {
println("This point is to the right of the line where x == 1.0")
}
// prints "This point is to the right of the line where x == 1.0"```

### 修改值类型的实例方法

```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)
println("The point is now at ((somePoint.x), (somePoint.y))")
// prints "The point is now at (3.0, 4.0)"```

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

### 由变异方法分配self

```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)
}
}```

moveByX方法的mutating 版本创建了一个全新的结构体，并将x和y的值设置到目标位置。调用这个版本的方法的最终返回结果和调用之前版本的结果完全一样。枚举的变异方法可以在同一个枚举里为隐式的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()
// ovenLight is now equal to .High
ovenLight.next()
// ovenLight is now equal to .Off```

### 类型方法

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

```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
}
}
}```

```class Player {
var tracker = LevelTracker()
let playerName: String
func completedLevel(level: Int) {
LevelTracker.unlockLevel(level + 1)
}
init(name: String) {
playerName = name
}
}```

```var player = Player(name: "Argyrios")
player.completedLevel(1)
println("highest unlocked level is now (LevelTracker.highestUnlockedLevel)")
// prints "highest unlocked level is now 2"```

```player = Player(name: "Beto")
{"ft_lang_label":"__label__zh","ft_lang_prob":0.85183024,"math_prob":0.96975094,"size":7079,"snap":"2019-13-2019-22","text_gpt3_token_len":3950,"char_repetition_ratio":0.12254417,"word_repetition_ratio":0.1342155,"special_character_ratio":0.18222913,"punctuation_ratio":0.13341804,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98541945,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-03-23T19:19:06Z\",\"WARC-Record-ID\":\"<urn:uuid:8af82092-7a82-4f3e-ac26-a78c6ba7b7fd>\",\"Content-Length\":\"29947\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:8ed74f2e-071f-4d58-a5ec-e87e07235c70>\",\"WARC-Concurrent-To\":\"<urn:uuid:d3e6aa6e-f47c-432c-8513-3765a53df248>\",\"WARC-IP-Address\":\"122.14.200.60\",\"WARC-Target-URI\":\"https://notes.clump.cc/technology/3271\",\"WARC-Payload-Digest\":\"sha1:IQKAHP2WGBABRFUM6VMV5UMPR2C6CG6F\",\"WARC-Block-Digest\":\"sha1:VDG3BEP7GYMLNRWPDZJP67ONAZAW37VB\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-13/CC-MAIN-2019-13_segments_1552912202924.93_warc_CC-MAIN-20190323181713-20190323203713-00201.warc.gz\"}"}