Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is type '()' in swift? [duplicate]

Tags:

swift

I'm receiving an event that passes a parameter of type ().

Is it an empty tuple..?

I'm referring to this type of expression:

let x = ()

like image 361
Shahar Avatar asked Mar 28 '17 14:03

Shahar


People also ask

What is NSCopying in Swift?

NSCopying can be used in Swift as a generic way to create copies of classes (reference types), and as a bonus, making a Swift type inherit from NSCopying will also allow it to make use of the copy property accessor in Objective-C bridges.

What is shallow copy and deep copy in Swift?

A copy of a class object is a shallow copy. Shallow copies are faster than deep copy, because of sharing the reference only. The created copy doesn't entirely create a new instance in memory, just address/reference is copied. As reference is shared, value change in a copy changes all the other.

How do I copy one array to another in Swift?

var duplicateArray = originalArray is all you need. Note that there are pitfalls here that Swift's value semantics are working to protect you from—for example, since NSArray represents an immutable array, its copy method just returns a reference to itself, so the test above would yield unexpected results.


2 Answers

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

let x = ()

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

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 with no parameters and/or no return value there seems to be a consensus to use () for an empty parameter list, and Void for no return value. This can for example be seen in UIKit completion handlers, or for execution blocks submitted to GCD dispatch queues, e.g.

func sync(execute block: () -> Void)
like image 116
Martin R Avatar answered Oct 10 '22 23:10

Martin R


Looking at the docs for the Swift grammar:

All tuple types contain two or more types, except for Void which is a 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­

Therefore yes, it is a tuple of zero types / elements.

like image 36
luk2302 Avatar answered Oct 11 '22 01:10

luk2302