Swift: assigning function to variable

后端 未结 1 1412
心在旅途
心在旅途 2021-02-12 13:00

I have a class in swift with the following variable:

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

Swift then tells me:

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-12 13:07

    The postfix .self expression just refers to the object it's an instance of. Kind of like .this in other languages. For types in particular, it tells the compiler that you're referring to the type itself, rather than instructing it to create a new instance of that type. If you'd like to know more, you can read all about it in the docs here. While useful in a lot of cases, it's not really needed here.

    As for your problem, when you assign:

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

    You're assigning the type of a particular sort of function as the value of the variable. From that, Swift infers that the type of the variable should be Type. Then later when you try to assign an actual function fitting that type as the value, it throws an error because it's expecting a type, not a function.

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

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

    Here's an example of the whole thing:

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

    0 讨论(0)
提交回复
热议问题