Swift Tuple index using a variable as the index?

前端 未结 5 902
灰色年华
灰色年华 2021-01-21 08:31

Swift Tuple index using a variable as the index? Anyone know if it is possible to use a variable as the index for a Swift tuple index. I wish to select and item from a tuple usi

5条回答
  •  难免孤独
    2021-01-21 09:18

    Make sure you've chosen the correct data structure

    If you've reached a point where you need to access tuple members as if "indexed", you should probably look over your data structure to see if a tuple is really the right choice for you in this case. As MartinR mentions in a comment, perhaps an array would be a more appropriate choice, or, as mentioned by simpleBob, a dictionary.

    Technically: yes, tuple members can be accessed by index-style

    You can make use of runtime introspection to access the children of a mirror representation of the tuple, and choose a child value given a supplied index.

    E.g., for 5-tuples where all elements are of same type:

    func getMemberOfFiveTuple(tuple: (T, T, T, T, T), atIndex: Int) -> T? {
        let children = Mirror(reflecting: tup).children
        guard case let idx = IntMax(atIndex)
            where idx < children.count else { return nil }
        
        return children[children.startIndex.advancedBy(idx)].value as? T
    }
    
    let tup = (10, 11, 12, 13, 14)
    let idx = 3
    
    if let member = getMemberOfFiveTuple(tup, atIndex: idx) {
        print(member)
    } // 13
    

    Note that the type of child.value is Any, hence we need to perform an attempted type conversion back to the element type of the tuple. In case your tuple contains different-type members, the return type cannot be known at compile time, and you'd probably have to keep using type Any for the returned element.

提交回复
热议问题