(1)参数类型为可选型Optional. 如果参数为空,则输出??后面的字符串,否则输出可选型的参数值。
import Foundation func sayHello(name:String?)->String{ let result = "Hello," + (name ?? "无名氏") return result } var nickname:String? nickname = "Jack" println(sayHello(nickname))
(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,90,45,3,213,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,score)//Swift中的全局函数; curmin = min(curmin,score) } return (curmax,curmin) } let result = maxMinScores(userScores) println("最大值:\(result.0)" ) println("最小值:\(result.1)" )
import Foundation let userScores = [12,90,45,3,213,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,score)//Swift中的全局函数; curmin = min(curmin,score) } return (curmax,curmin) } //返回的是一个可选型; if let result = maxMinScores(userScores){ println("最大值:\(result.maxScore)" ) println("最小值:\(result.minScore)" ) }
import Foundation var userScores:[Int]? = [1,2,3,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,score)//Swift中的全局函数; curmin = min(curmin,score) } return (curmax,curmin) } //返回的是一个可选型; userScores = userScores ?? [] if let result = maxMinScores(userScores!){ println("最大值:\(result.maxScore)" ) println("最小值:\(result.minScore)" ) }
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!