在进行 App 内部搜索或者筛选网络加载的 String 内容时, 需要对字符串进行过滤. 比如我们有一个 textField 让用户在此输入 nickName, 他或许会调皮的输入一堆空格. 这时候就需要我们对用户的输入进行检查, 符合标准才能通过. 下面我们为 String 类型增加一个 extension 完成这样的功能.
首先定义一个 enum, 用来表示不同的过滤规则.
1 2 3 4 5 6 7 8 9 10 11 12
| extension String { public enum TrimmingType { case whitespace case whitespaceAndNewLine case squashingWhiteSpace } }
|
之后我们在 String 的 extension 中增加一个 public 方法 trimming(with trimmingType: TrimmingType) -> String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public func trimming(with trimmingType: TrimmingType) -> String { switch trimmingType { case .whitespace: return trimmingCharacters(in: NSCharacterSet.whitespaces) case .whitespaceAndNewLine: return trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) case .squashingWhiteSpace: let compoents = components(separatedBy: NSCharacterSet.whitespaces).filter { !$0.isEmpty } return compoents.joined(separator: "") } }
|
OK! Done.
我们在外部使用时只需要用字符串实例直接调用自己的 trimming 方法就可以了.
1 2 3
| let string = " 测试字符串 " let resultString = string.trimming(trimmingType: .whitespace) print(resultString)
|