Skip to content

Instantly share code, notes, and snippets.

@aronskaya
Last active October 4, 2017 06:21
Show Gist options
  • Save aronskaya/04ba6b30fc10b0e738b576c378150b70 to your computer and use it in GitHub Desktop.
Save aronskaya/04ba6b30fc10b0e738b576c378150b70 to your computer and use it in GitHub Desktop.
[String+Extensions] #string
extension String {
/// Remove all whitespaces from the string
mutating func withoutWhitespaces() {
let array = components(separatedBy: .whitespaces)
self = array.joined()
}
/// Check if a string consists only of characters from a specified ChatacterSet
func hasOnly(charsFrom charSet: CharacterSet) -> Bool {
for char in unicodeScalars {
if !charSet.contains(char) {
return false
}
}
return true
}
/// Check if a string contains only valid for url host characters
func isValidHost() -> Bool {
if isEmpty {
return false
}
if !hasOnly(charsFrom: .urlHostAllowed) {
return false
}
return true
}
/// Generate a random string
static func randomString(length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment