How to Comprehend the "First-Class Function" in Swift

How to comprehend the first-class function in swift?

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.

“Functions are a first-class type” in swift?

A very simple example to demonstrate this behaviour:

func functionA() {
println("Hello by functionA")
}

func executeFunction(function: () -> ()) {
function()
}

executeFunction(functionA)

Swift any difference between Closures and First-Class Functions?

These notions are orthogonal. They are not directly related; they are two facts about functions in Swift.

  • Functions are first-class. This means they can be passed around — assigned as variables, passed into function parameters as arguments, and passed out of functions as results.

  • Functions are closures. This means that, at the point of definition, they capture the environment referred to inside the function body but declared outside the function body.

Here is an example (from a playground):

func multiplierMaker(i:Int) -> (Int) -> (Int) {
func multiplier(ii:Int) -> (Int) {
return ii*i
}
return multiplier
}
let g = multiplierMaker(10)
g(2) // 20

Think about the function multiplier:

  • The fact that multiplier can be returned as the result of the function multiplierMaker, and assigned to g, and that it has a well-defined type (Int) -> (Int), is because functions are first-class.

  • The fact that, when 10 is passed into multiplierMaker, the resulting multiplier function multiplies its parameter by 10, even when assigned to g and called later, is because functions are closures.

(Notice that this has nothing to do with anonymous functions. All answers or statements leading you to believe that closures have to do with anonymous functions are wrong. There are no anonymous functions in this example. An anonymous function is a closure, but only because all functions are closures.)

First class generic function in swift?

I realised, five years after asking this question, Swift supports something a little like this which can be useful via callAsFunction.

Here's an example:


final class Service<T> {
// Implementation here
}

final class Attacher {
// Important state here.
var state = Void()

func callAsFunction<T>(service: Service<T>, to: T) {
// Implementation here.
}
}

func doAttaching(attach: Attacher) {
attach(service: Service<Int>(), to: 42)
attach(service: Service<String>(), to: "Hello World!")
}

A Repeater can be passed in to generic code and provide useful behaviour.

What is the importance of class function in Swift?

If you want to call this Type Method, you write

Downloader.downloadImageWithURL(...)

If it is an Instance Method, you need to create a object first:

let downloader: Downloader = Downloader()
downloader.downloadImageWithURL(...)

In other languages (e.g. C++, Java) you would talk about static vs. non-static functions.

There is no advantage or disadvantages per se, it is an design decision, a very important one! A rule of thumb which came to my mind right now: If there is no need to maintain a state information, go for type methods, otherwise use instance methods.¹

Read more about these methods in Swift Langauge Reference.


¹ At the same time I wrote this rule of thumb, some counter examples came to my mind. So please consider this as a very rough rule of thumb and read some better introductions on object oriented design.

Swift mutating Function as first class value

The reason why you get a warning (and soon to be an error in Swift 5 mode) on:

extension Array where Element == Int { 
mutating func swapFirstTwo2() {
if count >= 2 {
swapAt(0, 1)
}
}
}

typealias Swapper2 = (inout [Int]) -> () -> ()
let swapThemAgain: Swapper2 = Array.swapFirstTwo2

is due to the fact that inout arguments are only valid for the duration of the call they're passed to, and therefore cannot be partially applied.

So if you were to call the returned (inout [Int]) -> () -> () with &array2, you would get back a () -> () which now has an invalid reference to array2. Attempting to call that function will yield undefined behaviour, as you're trying to mutate an inout argument outside of the window where it's valid.

This problem will be fixed if/when unapplied instance methods get flat signatures, as Array.swapFirstTwo2 will instead evaluate to a (inout [Int]) -> ().

But in the mean time, you can workaround the issue by using a closure instead:

typealias Swapper2 = (inout [Int]) -> ()
let swapThemAgain: Swapper2 = { $0.swapFirstTwo2() }

var array2 = [1,2,3]
print(array2) // [1, 2, 3]
array2.swapFirstTwo2()
print(array2) // [2, 1, 3]

How do I update a class variable from inside of a method for visibility of that variable to other classes in Swift?

Change your code in SecondClass like this:

Class SecondClass: UIViewController {

let myfirstClass = FirstClass()
myFirstClass.abc() // changes the tag in your instance of FirstClass

var a = myfirstClass.getTag()

// will print 5 because now you ask the instance,
// where the abc-function was called
}

The vocabulary of first class functions

First, to clarify the nomenclature.

The term "first class functions" means that it is "first class" in the type system: that is, that functions themselves are values. In languages where functions are not first class, functions are defined as a relationship between values, which makes them "second class".

Put another way, "first class" functions implies that you can use a function as a value, which means (among other things) that you can pass functions into functions. You couldn't do this in Java before Java 7 (reflection doesn't count), so that's an example of a programming language only having "second class" functions. In order to "pass a function", you had to define a type where that function could live (as a method), and then pass an instance of that type.

So, in Python, all functions are first class, because all functions can be used as a value.

Now, there is another concept which you might be getting confused with. There is also a concept of a "higher order function". A higher order function is a function that takes a function as an argument. Not all functions in Pythons are higher-order, because not all functions take another function as an argument. But even the functions that are not higher-order are first class. (It's a square/rectangle thing.)



Related Topics



Leave a reply



Submit