What is the type of '()' in swift?

I get an event that passes a parameter of type () .

Is this an empty tuple.?

I mean this type of expression:

let x = ()

+5
source share
3 answers

() is both a type (and Void is a type alias for an empty tuple type) and the only value of this type. So

 let x = () 

defines x as a property of a constant of type () (aka Void ) with a value of () .

Equivalent statements would be

 let x:() = () let x:Void = () 

but not

 let x = Void // error: expected member name or constructor call after type name 

because Void is a type, but not a value.

When defining function types without parameters and / or without a return value, it seems that there is agreement to use () for an empty parameter list, and Void without a return value. This can be seen, for example, in UIKit completion handlers or for execution blocks presented in GCD Send Queues, for example

 func sync(execute block: () -> Void) 
+4
source

Yes, this is an empty motorcade, aka Void .

The standard type of Void is defined as:

 typealias Void = () 

The return type of functions that do not explicitly indicate the return type; empty tuple (i.e. () ).

+2
source

Looking at the docs for a Swift grammar :

All tuple types contain two or more types, with the exception of Void , which is type alias for the empty tuple type, () .

 tuple-type → () | ( tuple-type-element , tuple-type-element-list ) tuple-type-element-list → tuple-type-element | tuple-type-element , tuple-type-element-list tuple-type-element → element-name type-annotation | type element-name → identifier 

So yes, this is a collection of null types / elements.

+2
source

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


All Articles