Applications of Custom Property Wrappers

May 18 2021 Swift 5.3, iOS 14, Xcode 12

Part 1: Applications of Custom Property Wrappers

3. Sanitize & Validate Data

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 2. Supercharge User Defaults Next episode: 4. Log Property Access

Code pasted in during this episode:

struct WhitespaceValidation: Validation {
  struct Options: OptionSet {
    let rawValue: Int

    static let trailing = Options(rawValue: 1 << 0)
    static let leading = Options(rawValue: 1 << 1)

    static let all: Options = [.leading, .trailing]
  }
  typealias Value = String
  let options: Options

  func validate(_ value: String) -> Bool {
    return !value.isEmpty
  }

  func sanitize(_ value: String) -> String {
    var value = value
    if self.options.contains(.leading) {
      while value.first?.isWhitespace == true {
        value.removeFirst()
      }
    }
    if self.options.contains(.trailing) {
      while value.last?.isWhitespace == true {
        value.removeLast()
      }
    }
    return value
  }

  static let trailing = WhitespaceValidation(options: .leading)
  static let leading = WhitespaceValidation(options: .trailing)
  static let all = WhitespaceValidation(options: .all)
}```