Created
February 10, 2021 14:59
-
-
Save joemasilotti/68e2b12af52f719dc06d097cf951c60f to your computer and use it in GitHub Desktop.
Two approached to a Swift enum with associated type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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