Last active
October 4, 2017 06:21
-
-
Save aronskaya/04ba6b30fc10b0e738b576c378150b70 to your computer and use it in GitHub Desktop.
[String+Extensions] #string
This file contains hidden or 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 { | |
/// 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