Reusable.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // Reusable.swift
  3. // QuickTableViewController
  4. //
  5. // Created by Ben on 21/08/2017.
  6. // Copyright © 2017 bcylin.
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining a copy
  9. // of this software and associated documentation files (the "Software"), to deal
  10. // in the Software without restriction, including without limitation the rights
  11. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. // copies of the Software, and to permit persons to whom the Software is
  13. // furnished to do so, subject to the following conditions:
  14. //
  15. // The above copyright notice and this permission notice shall be included in all
  16. // copies or substantial portions of the Software.
  17. //
  18. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. // SOFTWARE.
  25. //
  26. import UIKit
  27. extension UITableViewCell: Reusable {}
  28. internal protocol Reusable {
  29. static var reuseIdentifier: String { get }
  30. }
  31. internal extension Reusable {
  32. internal static var reuseIdentifier: String {
  33. let type = String(describing: self)
  34. return type.matches(of: String.typeDescriptionPattern).last ?? type
  35. }
  36. }
  37. internal extension String {
  38. internal static var typeDescriptionPattern: String {
  39. // For the types in the format of "(CustomCell in _B5334F301B8CC6AA00C64A6D)"
  40. return "^\\(([\\w\\d]+)\\sin\\s_[0-9A-F]+\\)$"
  41. }
  42. internal func matches(of pattern: String) -> [String] {
  43. let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
  44. #if swift(>=3.2)
  45. let fullText = NSRange(location: 0, length: count)
  46. #else
  47. let fullText = NSRange(location: 0, length: characters.count)
  48. #endif
  49. guard let matches = regex?.matches(in: self, options: [], range: fullText) else {
  50. return []
  51. }
  52. return matches.reduce([]) { accumulator, match in
  53. accumulator + (0..<match.numberOfRanges).map {
  54. #if swift(>=4)
  55. return (self as NSString).substring(with: match.range(at: $0))
  56. #else
  57. return (self as NSString).substring(with: match.rangeAt($0))
  58. #endif
  59. }
  60. }
  61. }
  62. }