Created
February 11, 2019 18:13
-
-
Save raxityo/1a165424caab719c6050b4724f60849e to your computer and use it in GitHub Desktop.
Sample class to demonstrate usage of `try?` in Swift
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 TokenGenerator { | |
internal struct TokenError: Error {} | |
private var canObtainToken = true | |
private var token = "TOKEN" | |
func obtainToken() throws -> String { | |
guard canObtainToken else { | |
throw TokenError() | |
} | |
canObtainToken = false | |
return token | |
} | |
func returnToken() { | |
canObtainToken = true | |
} | |
} | |
let tokenGenerator = TokenGenerator() | |
let token = try? tokenGenerator.obtainToken() | |
print(token) // Prints: Optional("TOKEN") | |
let tokenAgain = try? tokenGenerator.obtainToken() | |
print(tokenAgain) // Prints: nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment