How to convert Tuple to AnyObject in Swift

3 Solutions Collect From Internet About “How to convert Tuple to AnyObject in Swift”

How can I cast/convert a Tuple to AnyObject?

Simply put, you can’t. Only class types (or types that are bridged to Foundation class types) can be cast to AnyObject. A tuple is not a class type.

Of course there may be lots of other ways to accomplish whatever you’re really trying to accomplish. But as for your particular question, you can’t do it.

This is just a workaround.

You can create a class to wrap your tuple.

class TupleWrapper {
    let tuple : (String, Int)
    init(tuple : (String, Int)) {
        self.tuple = tuple
    }
}

Then you can write this:

func myMethod() {
    aMethodeThatICanNotChange {
        let a  = ("John",7)
        let myTupleWrapper = TupleWrapper(tuple: a)
        return myTupleWrapper
    }
}

Alternatively you can create a generic wrapper that can receive a value of any Type.

class GenericWrapper<T> {
    let element : T
    init(element : T) {
        self.element = element
    }
}

Hope this helps.

A tuple is an ordered list of elements, so you can transform it into an Array which conforms to AnyObject protocol

func myMethode() {
    aMethodeThatICanNotChange {
        // let a  = ("John",7)
        let b = ["Joth", 7]

        return b  // No error
    }
}

func aMethodeThatICanNotChange(closure: () -> AnyObject) {
    // do something with closure

}