简体   繁体   中英

Swift: Determine the type of this constant

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 ?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM