Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to return a function from another function in Swift [closed]

Tags:

ios

swift

What it the most common situation where you would want to return a function from a function in Swift?

In the code below I'm returning a function but I don't really see the purpose since the function I'm returning is inside the function who is returning it. The reason I'm confused is because we could accomplish the same thing with just one function.

func person () -> ((String, Int) -> String) {

  func info(name: String, age: Int) -> (String) {
    return "\(name) is \(age) old"
  }

  return info
}


let nathan = person()
nathan("Nathan", 3)

print(nathan("Nathan", 3))

Can someone point out common situations where you would want to return a function and probably illustrate it with a better example?

I want to understand this since this is fundamental for programming in general not just Swift (I think).

like image 541
fs_tigre Avatar asked Jan 08 '16 12:01

fs_tigre


1 Answers

A classic example would be in a calculator program, e.g.:

func operatorForString(str: String) -> ((Float, Float) -> Float)? {
    if str == "+" {
        return (+) // brackets required to clarify that we mean the function
    } else if str == "-" {
        return (-)
    } else if str == "*" {
        return (*)
    } else if str == "/" {
        return (/)
    } else if str == "**" {
        return pow // No brackets required here
    } else {
        return nil
    }
}

if let op = operatorForString("-") {
    let result = op(1, 2) // -1
}

It's rather contrived, but it illustrates the principle simply...

As an "exercise to the reader" try to do it as a Dictionary lookup, rather than repeated ifs :)

like image 55
Grimxn Avatar answered Oct 23 '22 09:10

Grimxn