How to comprehend the "first-class function" in swift?
Asked Answered
L

3

0

I am reading some books about the functional programming in swift. When I see some books said the function in swift is "first-class function" and I confused what is the meaning of the "first-class". Can anybody answer me or give me some example code?

Localism answered 13/3, 2015 at 0:47 Comment(0)
S
8

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.
Sufficiency answered 13/3, 2015 at 0:49 Comment(2)
and I think the block in objective-c , we also can assign a block to a local variable, and pass it as an argument to another function, can I think the block in objective-c is also first-class?Localism
Yes, Objective-C blocks are also first class.Debrahdebrecen
H
2

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.

Heddi answered 13/3, 2015 at 1:50 Comment(1)
I've got to agree the name 'first class' is a little vague. Would've preferred something like 'function reference' or something more descriptiveCartulary
T
1

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))")
Theodolite answered 11/9, 2015 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.