Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Two approached to a Swift enum with associated type
// Enum with manual parsing.
enum ScriptMessage {
case registerForRemoteNotifications
case showBackButton(url: URL)
case signOutCompleted
init?(body: [String: Any]) {
switch body["name"] as? String {
case "registerForRemoteNotifications":
self = .registerForRemoteNotifications
case "showBackButton":
guard
let urlString = body["url"] as? String,
let url = URL(string: urlString)
else { return nil }
self = .showBackButton(url: url)
case "signOutCompleted":
self = .signOutCompleted
default:
return nil
}
}
}
class ScriptMessage {
let name: Name
let data: [String: Any]?
init?(message: WKScriptMessage) {
guard
let body = message.body as? [String: Any],
let rawName = body["name"] as? String,
let name = Name(rawValue: rawName)
else { return nil }
self.name = name
self.data = body["data"] as? [String: Any]
}
}
extension ScriptMessage {
enum Name: String {
case registerForRemoteNotifications
case showBackButton
case signOutCompleted
}
var url: URL? {
switch name {
case .showBackButton:
let rawURL = data?["url"] as? String ?? ""
return URL(string: rawURL)
default:
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment