How to comprehend the “first-class function” in swift?

别说谁变了你拦得住时间么 提交于 2019-12-02 08:24:31

Functions are first-class citizens in Swift because you can treat a function like a normal value. For example, you can …

  • assign a function to a local variable,
  • pass a function as an argument to another function, and
  • return a function from a function.

Its just fancy terminology that is currently trendy. It just means that you can have a variable that holds a reference to a function.

Its been in programming forever; in C and Fortran you have pointers to functions. Typical use in both these languages is to pass a compare function into a sort function so that the sort function can sort any data type.

In some languages, e.g. Java, it appears that you don't have pointers to functions, but you do have pointers to interfaces. So you define a Comparable interface with a compare method and pass an instance of Comparable to your sort.

Nothing new, just confusing terminology for a familiar concept. Presumably to try and make the feature sound new and sexy.

William Kinaan

Please see my answer in this question. And I will add one more example (please check the example in that question first):

func operateMono( operand: String) -> (Double -> Double)?{
    switch operand{
    case "log10":
        return log
    case "log2":
        return log2
    case "sin":
        return sin
    case "cos":
        return cos
    default:
        return nil
    }
}

And the usage

var functionMono = operateMono("log10")
print ("log10 for 10 = \(functionMono!(10))")

functionMono = operateMono("log2")
print ("log2 for 10 = \(functionMono!(10))")

functionMono = operateMono("sin")
print ("sin 10 = \(functionMono!(10))")

functionMono = operateMono("cos")
print ("cos 10 = \(functionMono!(10))")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!