Milad Gholamhosseini
Milad Gholamhosseini

Reputation: 63

Accessing a method with specifying that a class does not have parameters

In a tutorial when I tried to refer to a class without specifying that it has no parameters, it did not allow me to reach a method on it.

NSNumberFormatter().numberFromString(display.text!)!.doubleValue

When I did not put () after NSNumberFormatter, it did not allow me to have doubleValue.

Upvotes: 0

Views: 27

Answers (1)

vacawama
vacawama

Reputation: 154641

numberFromString is an instance method, so you need to call it with an instance of the class.

NSNumberFormatter() creates an instance of the class; it is shorthand for NSNumberFormatter.init(). That is why:

NSNumberFormatter().numberFromString(display.text!)!.doubleValue

works.


When you call NSNumberFormatter.numberFromString, that returns a function that requires an instance of the class NSNumberFormatter to be turned into a function that you can then call with a String.

In a Playground, if you do:

let f = NSNumberFormatter.numberFromString

and then Option-click on f, you find that its type is:

let f: NSNumberFormatter -> (String) -> NSNumber?

Note that you could call the function like this:

NSNumberFormatter.numberFromString(NSNumberFormatter())(display.text!)!.doubleValue

because that supplies the needed instance of NSNumberFormatter to NSNumberFormatter.numberFromString to access the instance method.

Upvotes: 1

Related Questions