Failable Initializer in Swift
Level 4474 keystrokes
init? returns nil instead of an instance when the input is invalid. "https://example.com" is split into scheme and host, while "invalid" has no "://" and gives nil, so the code prints the parts and then true.
Swift code
// Foundation provides components(separatedBy:)1import Foundation// A custom struct named URL (it hides Foundation's URL)2struct URL {3 let scheme: String4 let host: String5 // init? makes the initializer failable: the result is URL?6 init?(urlString: String) { // return nil means initialization failed7 guard urlString.contains("://") else { return nil } // Splits at "://"; components(separatedBy:) comes from Foundation8 let parts = urlString.components(separatedBy: "://") // Requires exactly two non-empty parts9 guard parts.count == 2, !parts[0].isEmpty, !parts[1].isEmpty else { return nil } // Both properties must be set before the init succeeds10 self.scheme = parts[0]11 self.host = parts[1]12 }13}14 // if let unwraps the optional result: prints Scheme: https, Host: example.com15if let url = URL(urlString: "https://example.com") {16 print("Scheme: \(url.scheme), Host: \(url.host)")17}// "invalid" has no "://", so the init returns nil: prints true18print(URL(urlString: "invalid") == nil)Output
Scheme: https, Host: example.com true
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Swift code and how often they appear.
:× 11.× 10"× 10(× 9)× 9=× 8/× 6{× 5}× 5[× 4