How to convert Tuple to AnyObject in Swift

本秂侑毒 提交于 2019-12-04 10:14:29

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

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!