How can I convert an array to a tuple?

前端 未结 5 1467
慢半拍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:43

    if what you want to do is extract multiple value from array at the same time, maybe the following code could help you

    extension Array {
        func splat() -> (Element,Element) {
            return (self[0],self[1])
        }
    
        func splat() -> (Element,Element,Element) {
            return (self[0],self[1],self[2])
        }
    
        func splat() -> (Element,Element,Element,Element) {
            return (self[0],self[1],self[2],self[3])
        }
    
        func splat() -> (Element,Element,Element,Element,Element) {
            return (self[0],self[1],self[2],self[3],self[4])
        }
    }
    

    then you can use it like this

      let (first,_,third) = ( 0..<20 ).map { $0 }.splat()
    

    you can even write a codegen to generate the extension code

提交回复
热议问题