Can I extend Tuples in Swift?

◇◆丶佛笑我妖孽 提交于 2019-12-04 23:35:05

You cannot extend tuple types in Swift. According to Types, there are named types (which can be extended) and compound types. Tuples and functions are compound types.

See also (emphasis added):

Extensions
Extensions add new functionality to an existing class, structure, or enumeration type.

As the answer above states, you cannot extend tuples in Swift. However, rather than just give you a no, what you can do is box the tuple inside a class, struct or enum and extend that.

struct TupleStruct {
    var value: (Int, Int)
}
extension TupleStruct : Hashable {
    var hashValue: Int {
        return hash()
    }
    func hash() -> Int {
        var hash = 23
        hash = hash &* 31 &+ value.0
        return hash &* 31 &+ value.1
    }
}

func ==(lhs: TupleStruct, rhs: TupleStruct) -> Bool {
    return lhs.value == rhs.value
}

As a side note, in Swift 2.2, tuples with up to 6 members are now Equatable.

Details

  • Xcode 11.2.1 (11B500), Swift 5.1

Solution

struct Tuple<T> {
    let original: T
    private let array: [Mirror.Child]
    init(_ value: T) {
        self.original = value
        array = Array(Mirror(reflecting: original).children)
    }

    func getAllValues() -> [Any] { array.compactMap { $0.value } }
    func swap() -> (Any?, Any?)? {
        if array.count == 2 { return (array[1].value, array[0].value) }
        return nil
    }
}

Usage

let x = (1, "one")
let tuple = Tuple(x)
print(x)                                        // (1, "one")
print(tuple.swap())                             // Optional((Optional("one"), Optional(1)))
if let value = tuple.swap() as? (String, Int) {
    print("\(value) | \(type(of: value))")      // ("one", 1) | (String, Int)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!