您好,登錄后才能下訂單哦!
// 函數作為返回值
func addTen(x: Int) -> (Int -> Int){
func getNum(num2: Int) -> Int{
return num2 + x
}
return getNum
}
var x = addTen(10)
print(x(20))
// 函數作為參數
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool{
for item in list{
if condition(item){
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool{
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
// 返回Tuple(元組)的函數
func getTuple(arr: [Int]) -> (max: Int, min: Int, avg: Float, sum: Int)?{
if arr.count == 0{
return nil
}
var max: Int = arr[0]
var min: Int = arr[0]
var avg: Float = 0
var sum: Int = arr[0]
var index = 0
for item in arr{
index++
if item > max{
max = item
}
if item < min{
min = item
}
sum += item
}
avg = Float(sum / index);
return (max, min, avg, sum)
}
var arr = [9, 0, 11, 3, -5, -13, 99, 30]
if let result = getTuple(arr){
print("max: \(result.max), min: \(result.min), avg: \(result.avg), sum: \(result.sum)")
}
// 可變參數
func sum(nums: Int...) -> Int{
var sum = 0;
for item in nums{
sum += item
}
return sum
}
var x = sum()
var y = sum(9, 10)
var z = sum(1, 5, 9)
// 函數嵌套
func fifteen() -> Int{
var x = 10
func addFive(){
x += 5
}
addFive()
return x
}
var a = fifteen()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。