Swift Tuple index using a variable as the index?

前端 未结 5 844
灰色年华
灰色年华 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:22

    Reference: https://gist.github.com/ctreffs/785db636d68a211b25c989644b13f301

    In Swift 5:

    func tupleToArray(tuple: Tuple) -> [Value] {
        let tupleMirror = Mirror(reflecting: tuple)
        assert(tupleMirror.displayStyle == .tuple, "Given argument is no tuple")
        assert(tupleMirror.superclassMirror == nil, "Given tuple argument must not have a superclass (is: \(tupleMirror.superclassMirror!)")
        assert(!tupleMirror.children.isEmpty, "Given tuple argument has no value elements")
        return tupleMirror.children.compactMap { (child: Mirror.Child) -> Value? in
            let valueMirror = Mirror(reflecting: child.value)
            assert(valueMirror.subjectType == Value.self, "Given tuple argument's child type (\(valueMirror.subjectType)) does not reflect expected return value type (\(Value.self))")
            return child.value as? Value
        }
    }
    
    let sss: [String] = tupleToArray(tuple: ("

提交回复
热议问题