Search code examples
swiftenumsswift2reactive-cocoa

Return an enum with associated value where AnyObject is expected


I'm trying to use an enum with associated values to capture the result of a flow of Reactive Cocoa 2.5 RACSignal operations. The API specifies that signals contain AnyObject values. I get an error that Cannot convert value of type 'MyEnum' to expected argument type 'AnyObject!'. Is there any simple way to wrap my enum values in a reference so that this will work?


Solution

  • I suppose you have to ask if an enum is really the best option here. But if it is, can you not just create your own wrapper?

    enum MyEnum {
        case MyCase(String)
    }
    
    class MyEnumWrapper {
        var myEnum: MyEnum
    
        init(_ myEnum: MyEnum) {
            self.myEnum = myEnum
        }
    }
    
    func takeAnyObject(a: AnyObject!) {
    
        if let myEnumW = a as? MyEnumWrapper {
            print(myEnumW.myEnum)
        }
    
    }
    
    let tmp = MyEnumWrapper(.MyCase("Hello"))
    takeAnyObject(tmp)