说明:func 声明一个函数, ->用来分隔函数参数和返回值
//demo1 返回不同类型的值
func greet(name: String,what: String ) -> String{
return "Hello \(name), today is \(what)"
}
let string = greet("zhongkun","wednesday")
println("print: \(string)")
func getGasPrices() ->(Double,Double,Double){
return (1.1,2.1,3.1)
}
println("getGasPrices: \(getGasPrices())")
//传入不同的参数
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
//函数可以嵌套
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
println("nested Function: \(returnFifteen())");
//返回值类型可以是一个函数
func funcReturnTwo() -> (Int -> Int){
func addOne(number:Int) -> Int {
return number+1
}
return addOne
}
var addOneResult = funcReturnTwo()
let resultReturn = addOneResult(30)
println("functionReturn:\(resultReturn)")
//函数可以作为另一个函数的参数传入
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]
let resultParamterFunc = hasAnyMatches(numbers, lessThanTen)
println("funcionParamter:\(resultParamterFunc)")
//其他(目前还不太清楚)
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
下一章将讲解swift的对象和类
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。