Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Created February 10, 2021 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemasilotti/68e2b12af52f719dc06d097cf951c60f to your computer and use it in GitHub Desktop.
Save joemasilotti/68e2b12af52f719dc06d097cf951c60f to your computer and use it in GitHub Desktop.
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