swift学习记录(func)
来源:互联网 发布:java 在服务器生成pdf 编辑:程序博客网 时间:2024/06/11 18:42
对于函数(func),我只能说swift的func真是无所不能,参数数量可以不固定、可以返回函数类型、用函数做参数等等。下面就来看看做这些例子。
// Playground - noun: a place where people can play
import Cocoa
//函数定义
func greet(name:String, day:String) ->String {
return"Hello\(name), today is \(day)."
}
greet("Bob","Tuesday")
//返回多个
func getGasPrices() -> (Double,Double,Double) {
return (3.59,3.69,3.79)
}
getGasPrices()
//参数数目不固定
func sumOf(numbers:Int...)->Int {
var sum =0
for nbin numbers {
sum += nb
}
return sum
}
sumOf()
sumOf(42,548,325)
//函数可以当作参数传入另一个函数 例句中参数list是这么写的:list:Int[],但是我发现不行,就改成来list:Array<Int>,不知道是不是小bug。
// 后来发现是数组定义方式改变,list:Int[]应写为list:[Int]。总觉得看着怪怪的,好的,它又给我移植带来了不便!
func hasAnyMatches(list:Array<Int>,condition:Int -> Bool) ->Bool {
for itemin list {
if condition(item) {
returntrue
}
}
returnfalse
}
func lessThanTen(number:Int) ->Bool {
return number <10
}
var numbers = [20,19,2,6]
hasAnyMatches(numbers,lessThanTen)
//函数可以返回一个函数
func makeIncrementer() -> (Int ->Int) {
func addOne(number:Int) -> Int {
return1 + number
}
returnaddOne
}
var increment =makeIncrementer ()
increment(7)
- swift学习记录(func)
- swift简单学习之函数(func)
- swift func
- swift学习记录(开端)
- swift学习记录(Optional)
- swift学习记录(switch)
- swift学习记录(for)
- 操作 swift学习记录(-)
- swift学习记录(selector)
- swift学习记录(in)
- swift 学习记录(一)
- swift 学习记录(二)
- swift 学习记录(三)
- swift 学习记录(四)
- swift学习记录(String)
- swift学习记录(函数)
- swift学习记录(枚举)
- swift 学习记录(继承)
- 在windows server2008上安装oracle
- Ubuntu14.04安装wineqq国际版
- python 函数可变参数的使用
- 动态链表操作1
- G - Tempter of the Bone
- swift学习记录(func)
- 读写SD卡需要在app的manifest中添加
- Ubuntu 14.04安装搜狗输入法
- 动态链表操作2
- 旋转有序数组的二分查找
- Arduino vs Raspberry Pi vs BeagleBone
- Linux 基础
- UIimage 图片的处理:缩放,设定大小,存储,截图
- iOS关联,objc_getAssociatedObject, objc_setAssociatedObject