Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extension String {
- func uniqueColor() -> UIColor {
- do {
- // Change each non-hex character to 0
- let regex = try NSRegularExpression(pattern: "[^a-fA-F0-9]", options: NSRegularExpression.Options.caseInsensitive)
- let range = NSMakeRange(0, self.count)
- let nonHexString = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "0")
- // Add 0's to the string until its length is a multiple of 3
- var multipleOfThreeString = nonHexString
- while multipleOfThreeString.count % 3 != 0 {
- multipleOfThreeString.append("0")
- }
- // Divide string into 3 equal parts
- let equaLengthStrings = multipleOfThreeString.split(by: multipleOfThreeString.count / 3)
- // While the length of the sub-strings is greater than 2, and all three of the sub-strings begin with a 0, remove the leading 0s from each string.
- var nonStartingCeroString = equaLengthStrings
- while nonStartingCeroString[0].count > 2 && nonStartingCeroString[0].first == "0" && nonStartingCeroString[1].first == "0" && nonStartingCeroString[2].first == "0" {
- nonStartingCeroString[0].removeFirst()
- nonStartingCeroString[1].removeFirst()
- nonStartingCeroString[2].removeFirst()
- }
- // If the length of the sub-strings is still greater than 2, then truncate each substring to 2 characters.
- let r = nonStartingCeroString[0].prefix(2)
- let g = nonStartingCeroString[1].prefix(2)
- let b = nonStartingCeroString[2].prefix(2)
- let rgbString = r.appending(g).appending(b)
- return UIColor(hexString: rgbString)
- } catch {
- return UIColor.black
- }
- }
- func split(by length: Int) -> [String] {
- var startIndex = self.startIndex
- var results = [Substring]()
- while startIndex < self.endIndex {
- let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
- results.append(self[startIndex..<endIndex])
- startIndex = endIndex
- }
- return results.map { String($0) }
- }
- }
Add Comment
Please, Sign In to add comment