(1)参数类型为可选型Optional. 如果参数为空,则输出??后面的字符串,否则输出可选型的参数值。
import Foundation func sayHello(name:String?)->String{ let result = "Hello," + (name ?? "无名氏") return result } var nickname:String? nickname = "Jack" println(sayHello(nickname))
(2)函数如果没有返回值,可以在后面加上->Void。
(3)使用元祖让函数返回多个值。
import Foundation let userscores = [12,90,45,3,213,45] func maxMinscores(scores:[Int]) -> (maxscores:Int,minscores:Int){ var curmax = scores[0] var curmin = scores[0] for score in scores[1 ..< scores.count]{ curmax = max(curmax,score)//Swift中的全局函数; curmin = min(curmin,score) } return (curmax,curmin) } let result = maxMinscores(userscores) println("最大值:\(result.maxscores)" ) println("最小值:\(result.minscores)" )
或者:
import Foundation let userscores = [12,45] func maxMinscores(scores:[Int]) -> (Int,Int){ var curmax = scores[0] var curmin = scores[0] for score in scores[1 ..< scores.count]{ curmax = max(curmax,curmin) } let result = maxMinscores(userscores) println("最大值:\(result.0)" ) println("最小值:\(result.1)" )
上述例子如果返回值为空,则需要进行如下的优化:
import Foundation let userscores = [12,45] func maxMinscores(scores:[Int]) -> (maxscore:Int,minscore:Int)?{ //如果传入的参数数组为空,则返回nil; if scores.isEmpty{ return nil } var curmax = scores[0] var curmin = scores[0] for score in scores[1 ..< scores.count]{ curmax = max(curmax,curmin) } //返回的是一个可选型; if let result = maxMinscores(userscores){ println("最大值:\(result.maxscore)" ) println("最小值:\(result.minscore)" ) }
如果传入的数组参数为空,再次进行优化:
import Foundation var userscores:[Int]? = [1,2,4,5,6] func maxMinscores(scores:[Int]) -> (maxscore:Int,minscore:Int)?{ //如果传入的参数数组为空,则返回nil; if scores.isEmpty{ return nil } var curmax = scores[0] var curmin = scores[0] for score in scores[1 ..< scores.count]{ curmax = max(curmax,curmin) } //返回的是一个可选型; userscores = userscores ?? [] if let result = maxMinscores(userscores!){ println("最大值:\(result.maxscore)" ) println("最小值:\(result.minscore)" ) }
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!