Swift心得笔记之函数

2020-01-08 22:50:29丽君

柯里化背后的基本想法是,函数可以局部应用,意思是一些参数值可以在函数调用之前被指定或者绑定。这个部分函数的调用会返回一个新的函数。

这个具体内容可以参见 Swift 方法的多面性 中 柯里化部分的内容。我们可以这样调用:

 

复制代码
class MyHelloWorldClass {
    func helloWithName(name: String) -> String {
        return "hello, (name)"
    }
}
let myHelloWorldClassInstance = MyHelloWorldClass()
let helloWithNameFunc = MyHelloWorldClass.helloWithName
helloWithNameFunc(myHelloWorldClassInstance)("Mr. Roboto")
// hello, Mr. Roboto

 

多返回值

在 Swift 中我们可以利用 tuple 返回多个返回值。比如下面这个例子,返回所有数字的范围:

 

复制代码
 func findRangeFromNumbers(numbers: Int...) -> (min: Int, max: Int) {
    var maxValue = numbers.reduce(Int.min,  { max($0,$1) })
    var minValue = numbers.reduce(Int.max,  { min($0,$1) }) 
    return (minValue, maxValue)
}
findRangeFromNumbers(1, 234, 555, 345, 423)
// (1, 555)

 

而返回值未必都是有值的,我们也可以返回可选类型的结果:

 

复制代码
import Foundation
func componentsFromUrlString(urlString: String) -> (host: String?, path: String?) {
    let url = NSURL(string: urlString)
    return (url?.host, url?.path)
}
let urlComponents = componentsFromUrlString("http://www.easck.com/> case let (.Some(host), .Some(path)):
    println("host (host) and path (path)")
case let (.Some(host), .None):
    println("only host (host)")
case let (.None, .Some(path)):
    println("only path (path)")
case let (.None, .None):
    println("This is not a url!")
}
// "host why and path /233/param"

 

以上所述就是本文的全部内容了,希望大家能够喜欢。



注:相关教程知识阅读请移步到swift教程频道。