Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I extend Tuples in Swift?

I'd like to write an extension for tuples of (e.g.) two value in Swift. For instance, I'd like to write this swap method:

let t = (1, "one")
let s = t.swap

such that s would be of type (String, Int) with value ("one", 1). (I know I can very easily implement a swap(t) function instead, but that's not what I'm interested in.)

Can I do this? I cannot seem to write the proper type name in the extension declaration.

Additionally, and I suppose the answer is the same, can I make a 2-tuple adopt a given protocol?

like image 542
Jean-Philippe Pellet Avatar asked Feb 04 '15 09:02

Jean-Philippe Pellet


People also ask

Are tuples mutable in Swift?

A tuple's values can have different types, and you can change their values, provided it's declared as mutable with var. But, after initialization, you can't add any more items to it.

Are tuples hashable Swift?

The reason that tuples cannot be used as keys (or specifically, are not hashable ) is because they are not strictly immutable.

Are tuples Equatable Swift?

But you can't use the contains() method: a. contains((3, 4)) // no!

Can tuples have different data types Swift?

You can create tuples from as many values as you want and from any number of different data types.


1 Answers

You cannot extend tuple types in Swift. According to Types, there are named types (which can be extended) and compound types. Tuples and functions are compound types.

See also (emphasis added):

Extensions
Extensions add new functionality to an existing class, structure, or enumeration type.

like image 180
Martin R Avatar answered Sep 29 '22 14:09

Martin R