📜  Swift方法

📅  最后修改于: 2021-01-11 07:58:10             🧑  作者: Mango

#### 句法：

``````func funcname(Parameters) -> returntype {
Statement1
Statement2
---
Statement N
return parameters
}
``````

#### 例：

``````class calculate {
let a: Int
let b: Int
let res: Int
init(a: Int, b: Int) {
self.a = a
self.b = b
res = a + b
}
func tot(c: Int) -> Int {
return res - c
}
func result() {
print("Result is: \(tot(c: 20))")
print("Result is: \(tot(c: 50))")
}
}
let pri = calculate(a: 200, b: 300)
pri.result()
``````

``````Result is: 480
Result is: 450
``````

• init()被定义为将两个数字a和b相加并将其存储在结果'res'中。
• tot()用于从传递的'c'值中减去'res'。

#### 例

``````class divide {
var count: Int = 0
func incrementBy(no1: Int, no2: Int) {
count = no1 / no2
print(count)
}
}
let counter = divide()
counter.incrementBy(no1: 100, no2: 3)
counter.incrementBy(no1: 200, no2: 5)
counter.incrementBy(no1: 400, no2: 7)
``````

``````33
40
57
``````

#### 例

``````class calculate {
let a: Int
let b: Int
let res: Int
init(a: Int, b: Int) {
self.a = a
self.b = b
res = a + b
print("Result Inside Self Block: \(res)")
}
func tot(c: Int) -> Int {
return res - c
}
func result() {
print("Result is: \(tot(c: 20))")
print("Result is: \(tot(c: 50))")
}
}
let pri = calculate(a: 100, b: 200)
let sum = calculate(a: 300, b: 400)
pri.result()
sum.result()
``````

``````Result Inside Self Block: 300
Result Inside Self Block: 700
Result is: 280
Result is: 250
Result is: 680
Result is: 650
``````

#### 例

``````struct area {
var length = 1
func area() -> Int {
}
mutating func scaleBy(res: Int) {
length *= res
print(length)
}
}
var val = area(length: 3, breadth: 5)
val.scaleBy(res: 2)
val.scaleBy(res: 20)
val.scaleBy(res: 200)
``````

``````6
10
120
200
24000
40000
``````