函数定义与调用(Defining and Calling Functions)
函数参数与返回值(Function Parameters and Return Values)
函数参数名称(Function Parameter Names)
//: Playground - noun: a place where people can play
import UIKit
//定义一个带参数的函数
// \()是用来替换变量值
func sayHello(personName: String ) -> String {
let greeting = "Hello,\(personName)"
return greeting
}
print(sayHello("luopan"))
//定义一个无参数的函数
func sayHello() ->String {
return "hello,swift!"
}
print(sayHello())
func sayHello(personName:String,alreadyGreed:Bool)->String{
if alreadyGreed{
return sayHello("第二次\(personName)")
}else{
return sayHello("第一次\(personName)")
}
}
print(sayHello("luopan",alreadyGreed: false))
print(sayHello("luopan",alreadyGreed: true))
//定义返回元祖,从而达到返回多个值的效果
func minMax(array:[Int]) -> (min:Int,max:Int){
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count]{
if value < currentMin {
currentMin = value
}else if value > currentMax{
currentMax = value
}
}
return (currentMin,currentMax)
}
let bounds = minMax([6,-2,4,456,3,78])
print("min is \(bounds.min) and max is \(bounds.max)")
//定义可选性元祖作为返回
func minMax(array:[Double]) -> (min:Double,max:Double)?{
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count]{
if value < currentMin {
currentMin = value
}else if value > currentMax{
currentMax = value
}
}
return(currentMin,currentMax)
}
//那么我们使用的时候需要解包可选型
if let minMaxValue = minMax([23.34,-34,78,45.56,545.00,333.444]){
print("min is \(minMaxValue.min) and max is \(minMaxValue.max)")
}
//定义一个具有外部参数名和局部变量名的函数
func sayHello(to person:String,and anotherPerson:String) ->String{
return "Hello \(person) and \(anotherPerson)"
}
//注意,如果指定了外部参数变量名,那么调用的时候,必须带上的。
print(sayHello(to: "luopan",and: "mingxing"))
//定义一个可变参数个数的函数
func arithmeticMean(numbers:Double...) -> Double{
var total:Double = 0
for number in numbers{
total += number
}
return total/Double(numbers.count)
}
//注意一个函数只能有一个可变参数
print(arithmeticMean(1,2,5))
print(arithmeticMean(3,8.26,18.75))
今天到此为止吧!