Last active
March 1, 2019 07:27
-
-
Save shengyang998/3c5108b425cc08c37224440e92937fc7 to your computer and use it in GitHub Desktop.
Swift String Extension: Can convert to url
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
```swift | |
extension String { | |
/// - Returns a Bool to determine if a string can be converted to a valid url | |
func canConvertToURL() -> Bool { | |
if let url = URL(string: self) { | |
return UIApplication.shared.canOpenURL(url) | |
} else { return false } | |
} | |
/// - Returns a URL if the string can be converted to a valid url, | |
/// and a `nil` if it failed | |
func convertToURL() -> URL? { | |
if let url = URL(string: self) { | |
if UIApplication.shared.canOpenURL(url) { return url } | |
else { return nil } | |
} else { return nil } | |
} | |
var url: URL? { | |
return convertToURL() | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment