Swift函数

简介: <div><p><span style="font-size:14px;">函数定义</span></p><p><span style="font-size:14px;"> </span></p><p><span style="font-size:14px;">使用 func 定义一个函数。调用函数使用他的名字加 上小括号中的参数列表。使用 -> 分隔参数的名字和 返回值类型。</

函数定义

 

使用 func 定义一个函数。调用函数使用他的名字加 上小括号中的参数列表。使用 -> 分隔参数的名字和 返回值类型。

 

函数声明:

 

func greet(name: String, day: String) -> String {
return "Hello \(name),today is \(day)."
 
} 

函数调用:greet("Bob", "Tuesday")

 

无返回值函数

func sayGoodbye(personName: String) {
println("Goodbye, \(personName)!")
}
sayGoodbye("Tony")

多返回值函数

 

使用元组类型返回多个值:

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)
}
let total = count("somearbitrary string!") 
println("\(total.vowels) 元音 , \(total.consonants) 辅 音")

嵌入函数

 

函数嵌套: 相当于函数指针

 

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
}
var currentValue = -4
let               moveNearerToZero                    =
chooseStepFunction(currentValue> 0)
while currentValue != 0{
println("\(currentValue)... ") 
currentValue = moveNearerToZero(currentValue)
}

Swift交流讨论论坛论坛:http://www.cocoagame.net

欢迎加入Swift技术交流群:362298485



目录
相关文章
|
4小时前
|
存储 Swift
Swift 语言:什么是闭包(Closure)?它们与函数的区别是什么?
Swift 语言:什么是闭包(Closure)?它们与函数的区别是什么?
40 1
|
4小时前
|
Swift
Swift中的函数
Swift中的函数
22 1
|
4小时前
|
存储 Swift
Swift中,函数和闭包
Swift中,函数和闭包
35 1
|
7月前
|
Swift iOS开发
23 Swift中如何定义和使用函数
Swift中如何定义和使用函数
54 0
|
8月前
|
Swift
Swift Debug 和 Release 中 print() 函数调试切换
Swift Debug 和 Release 中 print() 函数调试切换
44 0
|
Swift C语言
深入浅出Swift(3)—— 函数
深入浅出Swift(3)—— 函数
64 0
|
Swift C语言
【Swift 5.1】流程控制、函数与内联函数优化
文章目录 1.流程控制 1.1 while循环 eg1. 简单的打印例子1
|
缓存 前端开发 Swift
Swift实用小册06:函数的定义、参数、返回、调用
Swift实用小册06:函数的定义、参数、返回、调用
202 0
Swift实用小册06:函数的定义、参数、返回、调用
【Swift4】(5) 函数基本使用 | 可变参数 | inout引用传递 | 函数类型返回值 | 函数嵌套
【Swift4】(5) 函数基本使用 | 可变参数 | inout引用传递 | 函数类型返回值 | 函数嵌套
160 0
|
存储 编译器 Swift
Swift5.0 - day2-流程控制、函数、枚举(下)
Swift5.0 - day2-流程控制、函数、枚举(下)
68 0
Swift5.0 - day2-流程控制、函数、枚举(下)

相关课程

更多