Sayaki
Sayaki

Reputation: 789

Custom key failure in Swift

I'm trying to use custom class as a key in NSDictionary. To do that, as per compiler, I need to implement NSCopying protocol. I follow with this advice but it seems to not working. Here is my code:

My protocol what my key class conforms:

// My custom protocol
protocol TestProtocol: NSCopying {
    func testFunc()
}

When I'm implementing NSCopying protocol to class returning itself everything seems to work just fine:

// Custom key class
class KeyClass: NSObject, TestProtocol {
    func testFunc() {
    }

    func copyWithZone(zone: NSZone) -> AnyObject {
        return self
    }
}

Now when I'm invoking code:

    let key = KeyClass()
    let dictionary = NSMutableDictionary()

    dictionary.setObject("TestString", forKey: key)

    let value = dictionary[key]

Value contains "TestString"

but when I change KeyClass implementation to this from another stack topic like that:

class KeyClass: NSObject, TestProtocol {
    func testFunc() {
    }

    required override init() {
    }

    required init(_ model: KeyClass) {
    }

    func copyWithZone(zone: NSZone) -> AnyObject {
        return self.dynamicType.init(self)
    }
}

I'm keep getting nil in value variable. Can anyone explain to me why above implementation is not working?

Upvotes: 0

Views: 61

Answers (1)

Lumialxk
Lumialxk

Reputation: 6379

I guess protocol inheritor is not available for OC objects. So try swift dictionary like [KeyClass:String] or don't inherit any protocol.

Upvotes: 1

Related Questions