Swift: assigning a variable to a variable

I have a class in swift with the following variable:

var pendingFunction = ((Double, Double) -> Double) 

Swift tells me:

The expected member name or constructor call after the type name

He insists on changing his code to:

 var pendingFunction = ((Double, Double) -> Double).self 

I don't know what this .self thing does (sorry I'm new to Swift)

Then I try to assign a pendingFunction new function:

 pendingFunction = function 

where function takes two doubles and returns Double.

However, the following error was presented to me:

Cannot set value to type '(Double, Double) → Double' to type '((Double, Double) → Double) .Type'

So my question is: what does the .self thing do, and how can I properly assign a function to a variable?

+5
source share
1 answer

The .self expression simply refers to the object that it is an instance of. View as .this in other languages. For types, in particular, it tells the compiler that you are referring to the type itself, and not to telling it to create a new instance of this type. If you want to know more, you can read all about it in the docs here . Although useful in many cases, it really is not needed here.

As for your problem, when you assign:

 var pendingFunction = ((Double, Double) -> Double).self 

You assign the type of a particular function as the value of a variable. It follows that Swift indicates that the type of the variable should be Type . Then, when you try to assign the actual function corresponding to this type as a value, it throws an error because it expects a type, not a function.

Instead of assigning the type as a value, you want to declare a variable with this type as your type:

 var pendingFunction: ((Double, Double) -> Double) 

Here is an example of everything:

 var pendingFunction: ((Double, Double) -> Double) func myAdditionFunction (first: Double, second: Double) -> Double { return first + second } pendingFunction = myAdditionFunction print(pendingFunction(1,2)) // prints "3.0" 
+10
source

Source: https://habr.com/ru/post/1267158/


All Articles