Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Tuple to AnyObject in Swift

Tags:

swift

tuples

Following piece of code compiles with error: Error:(112, 20) type '(String, Int)' does not conform to protocol 'AnyObject'

func myMethode() {
    aMethodeThatICanNotChange {
        let a  = ("John",7)
        return a  // Error:(112, 20) type '(String, Int)' does not conform to protocol 'AnyObject'
    }
}

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

How can I cast/convert a Tuple to AnyObject?

like image 761
Enceradeira Avatar asked Dec 01 '22 00:12

Enceradeira


2 Answers

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.

like image 178
Luca Angeletti Avatar answered Dec 05 '22 04:12

Luca Angeletti


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.

like image 31
matt Avatar answered Dec 05 '22 02:12

matt