Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an array to a tuple?

Tags:

I just want to convert an array into a tuple in Swift; something like the following:

>>> myArray = [1,2,3,4,5] >>> mytuple = tuple(myArray) >>> mytuple (1, 2, 3, 4, 5) 

What's the easiest way of doing that?

(I only started learning Swift today, so I am very, very new).

like image 756
niranjanbajgai Avatar asked Jul 14 '14 21:07

niranjanbajgai


People also ask

How do I turn an array into a tuple in Python?

1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.

How would you convert a list into a tuple?

Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.

How do you convert a list to a tuple of tuples?

A simple way to convert a list of lists to a list of tuples is to start with an empty list. Then iterate over each list in the nested list in a simple for loop, convert it to a tuple using the tuple() function, and append it to the list of tuples.

Can a tuple be an array?

The Tuple type represents a JavaScript array where you can define the data type of each element in the array. a tuple is a special type of array that stores multiple fields belonging to the different data types into the same collection. It is similar to the structures in the c programming language.


1 Answers

It's actually quite possible, if you are willing to do some low level magic. I don't think it works if the tuple has a collection type, though. This is mainly for interacting with C libraries.

typealias TupleType = (UInt8, UInt8, UInt8)  var array = [2, 3, 4] as [UInt8] var tuple = UnsafeMutablePointer<StepsType>(malloc(UInt(sizeof(TupleType)))) memcpy(tuple, array, UInt(array.count)) 

More of this stuff can be found here: https://codereview.stackexchange.com/questions/84476/array-to-tuple-in-swift/84528#84528


Because 70% of us are highly visual beings:

enter image description here

like image 58
Mazyod Avatar answered Oct 02 '22 00:10

Mazyod