<span style="font-size:18px;">
//1.返回元组的函数 参数 : 字符串 返回 : 元组
func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
var vowels = 0, consonants = 0, others = 0
for character in string {
switch String(character).lowercaseString {
case "a", "e", "i", "o", "u":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
++consonants
default:
++others
}
}
return (vowels, consonants, others)
}
//2.基本函数 参数 : 字符串 返回 : 字符串
func sayHello(name : String) -> String {
return "wyl say hello to " + name
}
//3.给函数参数外部命名
func add (one one1 : Int , two two1 : Int ) -> Int{
return one1 + two1
}
//4. 给外部参数名默认值
func add2 (one one1 : Int , two two1 : Int = 0) -> Int{
return one1 + two1
}
//5. 不是外部参数带有默认值 调用必须是这样的 let result2 = add3(2,two : 1) 带上label
func add3 (one : Int , two : Int = 0) -> Int {
return one + two
}
//6. 可变参数
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
//7.输入输出参数
func changeNum(inout x : Int , inout y : Int){
let temporaryA = x
x = y
y = temporaryA
}
//8.函数类型
func addTwoInts(a: Int, b: Int) -> Int {
return a + b
}
//9.嵌套函数与返回函数
//参数 为一个bool 返回一个参数为int 返回值为int的函数
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward : stepForward
}
override func viewDidLoad() {
super.viewDidLoad()
println(sayHello("jack"))
let yuanzu = count("wyl")
println("\(yuanzu.vowels) vowels and \(yuanzu.consonants) consonants")
let result = add(one :1, two :2)
println(result)
let result1 = add2(one :1)
println(result1)
let result2 = add3(2,two : 1)
println(result2)
var x1 = 10
var y1 = 20
changeNum(&x1,y:&y1)
var math : (Int, Int) -> Int = addTwoInts
println(math(1,5))
}
</span>
Swift学习 --- 2.6函数
最新推荐文章于 2025-07-22 14:09:33 发布