How can I convert an array to a tuple?

前端 未结 5 1456
慢半拍i
慢半拍i 2020-12-03 07:12

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)         


        
5条回答
  •  不思量自难忘°
    2020-12-03 07:44

    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(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

提交回复
热议问题