Created
November 14, 2017 15:09
-
-
Save alobanov/30dec2f118532b4cc32d82bc321ac1bd to your computer and use it in GitHub Desktop.
Middleware example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CheckNilMiddleware: Middleware { | |
override func check(value: MiddlewareItem) -> MiddlewareItem { | |
switch value { | |
case .value(let str): | |
if str == nil { | |
return .error("Значение равно nil") | |
} | |
default: break | |
} | |
return checkNext(value: value) | |
} | |
} | |
class CheckCountMiddleware: Middleware { | |
private let length: Int | |
init(length: Int) { | |
self.length = length | |
} | |
override func check(value: MiddlewareItem) -> MiddlewareItem { | |
switch value { | |
case .value(let str): | |
if str?.count != length { | |
return .error("Длинна должна быть \(length)") | |
} | |
default: break | |
} | |
return checkNext(value: value) | |
} | |
} | |
class PhoneFormatterMiddleware: Middleware { | |
private let format: String // "+X (XXX) XXX XX-XX" | |
init(format: String) { | |
self.format = format | |
} | |
override func check(value: MiddlewareItem) -> MiddlewareItem { | |
switch value { | |
case .value(let str): | |
if let s = str { | |
let cleanPhoneNumber = s.components(separatedBy: CharacterSet.decimalDigits.inverted).joined() | |
let mask = format | |
var result = "" | |
var index = cleanPhoneNumber.startIndex | |
for ch in mask { | |
if index == cleanPhoneNumber.endIndex { | |
break | |
} | |
if ch == "X" { | |
result.append(cleanPhoneNumber[index]) | |
index = cleanPhoneNumber.index(after: index) | |
} else { | |
result.append(ch) | |
} | |
} | |
return .value(result) | |
} | |
default: break | |
} | |
return checkNext(value: value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment