hackphone hackphone - 1 year ago 83
Swift Question

Swift Closure compilation error

I am a beginner in swift.

The following code does not have any compilation error

var test = { //no error
return "String"

Whereas if I add the type String to the variable test as shown below, the compiler throws error "Function produces expected type string. Did you mean to call it with ()"

var test:String = { // error
return "String"

As far as I know, swift is capable of type inference. Can someone please explain why the above code throws compilation error where the first one doesn't.


Answer Source

In your first example, Swift correctly uses type inference to infer your closure as a zero-argument (Void/empty tuple ()) closure with return value String: () -> String

var test  =  {
    return "String"

print(test.dynamicType) // () -> String

Whereas in your second example, you explicitly specify that the type of test is String, which means the attempt to assign a closure of type () -> String to it will be a type mismatch.

The reason Swift asks you if you'd like to call the closure with () is that you can actually call the closure a single time (much like you call a function with a function reference an an argument list (...)), using the return value of the closure (which is String) to assign an initial value to your test variable (which is of, just that, type String).

var test2: String  =  {
    return "String"
}() // ok! assign "String" to test2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download