Swift enums as a dictionary key

I recently added a WatchOS target to an existing iOS application that uses SwiftUI and I wanted to have the two platforms communicate with one another. This isn’t so much about the actual communication setup, but rather using an enum as a dictionary key.

This prevents developers from using hand-typed strings as keys where mistakes can be made. It doesn’t read well, and you get no Xcode autocomplete that way either. So here is an example enum. Keys need to be of type String.

Swift

That syntactical sugar allows us to use an enum as a String instance and thus or normal calls only have to be modified slightly, but you’ll see how this improves things.

Swift

Here is a sendMessage on the WCSession

Swift

It’s a tiny bit ugly using the DeviceMessageRawKey function, but it allows you to use the enums in sending and evaluating received messages. That’s what you want. And it works.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.