Applications of Custom Property Wrappers

May 18 2021 · Swift 5.3, iOS 14, Xcode 12

Part 1: Applications of Custom Property Wrappers

03. Sanitize & Validate Data

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 02. Supercharge User Defaults Next episode: 04. Log Property Access

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 03. Sanitize & Validate Data

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)
}```