Created
October 24, 2016 11:32
-
-
Save klein-artur/de85528b34777b4d433df28a76ced9b0 to your computer and use it in GitHub Desktop.
String extension to get a substring by UInt indexes.
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
extension String { | |
func substring(from: UInt, length: UInt) -> String { | |
if Int(from) >= self.characters.count { | |
preconditionFailure("from is out of bounds.") | |
} | |
if Int(from+length) > self.characters.count { | |
preconditionFailure("from and lenght are out of bounds") | |
} | |
let startIndex = self.index(self.startIndex, offsetBy: String.IndexDistance(from)) | |
let endIndex = self.index(self.startIndex, offsetBy: String.IndexDistance(from+length)) | |
return self.substring(with: startIndex..<endIndex) | |
} | |
func substring(from: UInt) -> String { | |
if Int(from) >= self.characters.count { | |
preconditionFailure("from is out of bounds.") | |
} | |
let startIndex = self.index(self.startIndex, offsetBy: String.IndexDistance(from)) | |
return self.substring(from: startIndex) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment