Guest User

Untitled

a guest
Sep 18th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. extension String {
  2. func uniqueColor() -> UIColor {
  3. do {
  4. // Change each non-hex character to 0
  5. let regex = try NSRegularExpression(pattern: "[^a-fA-F0-9]", options: NSRegularExpression.Options.caseInsensitive)
  6. let range = NSMakeRange(0, self.count)
  7. let nonHexString = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "0")
  8.  
  9. // Add 0's to the string until its length is a multiple of 3
  10. var multipleOfThreeString = nonHexString
  11. while multipleOfThreeString.count % 3 != 0 {
  12. multipleOfThreeString.append("0")
  13. }
  14.  
  15. // Divide string into 3 equal parts
  16. let equaLengthStrings = multipleOfThreeString.split(by: multipleOfThreeString.count / 3)
  17.  
  18. // 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.
  19. var nonStartingCeroString = equaLengthStrings
  20. while nonStartingCeroString[0].count > 2 && nonStartingCeroString[0].first == "0" && nonStartingCeroString[1].first == "0" && nonStartingCeroString[2].first == "0" {
  21. nonStartingCeroString[0].removeFirst()
  22. nonStartingCeroString[1].removeFirst()
  23. nonStartingCeroString[2].removeFirst()
  24. }
  25.  
  26. // If the length of the sub-strings is still greater than 2, then truncate each substring to 2 characters.
  27. let r = nonStartingCeroString[0].prefix(2)
  28. let g = nonStartingCeroString[1].prefix(2)
  29. let b = nonStartingCeroString[2].prefix(2)
  30.  
  31. let rgbString = r.appending(g).appending(b)
  32. return UIColor(hexString: rgbString)
  33. } catch {
  34. return UIColor.black
  35. }
  36. }
  37.  
  38. func split(by length: Int) -> [String] {
  39. var startIndex = self.startIndex
  40. var results = [Substring]()
  41.  
  42. while startIndex < self.endIndex {
  43. let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
  44. results.append(self[startIndex..<endIndex])
  45. startIndex = endIndex
  46. }
  47. return results.map { String($0) }
  48. }
  49. }
Add Comment
Please, Sign In to add comment