How to convert Tuple to AnyObject in Swift

折月煮酒 提交于 2019-12-06 04:54:28

问题


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?


回答1:


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.




回答2:


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.




回答3:


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

}


来源:https://stackoverflow.com/questions/28139302/how-to-convert-tuple-to-anyobject-in-swift

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