Home > other >  Swift: Determine the type of this constant
Swift: Determine the type of this constant

Time:06-27

What is exactly the type of this const (val)?

let val = { (a: Int, b:Int)->Int in a   b }(1 , 2)

Isn't it (Int,Int) -> Int ?

CodePudding user response:

It is just Int, because it takes only the final result, you call a function there that takes 2 Ints and return their adding result, which is going to be 3

In order to determine the type of a variable in the future you could just hold option key on the keyboard and hover over the variable name

CodePudding user response:

There's already a good answer here, but I'd like to provide some more details for the records.

The following is a closure expression of type (Int, Int)->Int:

{ (a: Int, b:Int)->Int in a   b }

You could as well have defined an equivalent named function:

func f (_ a: Int, _ b:Int)->Int { a b }

You could then have called the function with two parameters to get an Int value:

let val = f(1,2) 

And you can do the same thing by replacing the function name with a closure expression:

let val = { (a: Int, b:Int)->Int in a   b }(1 , 2)

You could even combine the two practice and display step by step the type:

let l = { (a: Int, b:Int)->Int in a   b }    // name the closure using a variable
print (type(of: l))                          // (Int, Int)->Int
let val = l(1 , 2)                           // use the closure 
print (type(of: val))                        // Int
print (val)
  • Related