如何将Swift字符串指定字符移除逻辑封装为可复用Extension
Swift String 移除指定字符扩展实现方案
你可以给String添加两个扩展方法,分别覆盖原地修改、返回新字符串两种常用场景:
extension String { /// 原地移除当前字符串中属于指定字符集合的所有字符 mutating func removeCharacters(in characterSet: Set<Character>) { removeAll(where: { characterSet.contains($0) }) } /// 生成并返回移除了指定字符集合中所有字符的新字符串 func removingCharacters(in characterSet: Set<Character>) -> String { self.filter { !characterSet.contains($0) } } }
使用示例
对应你原有的业务逻辑,调用方式如下:
var string = "11224B" let removeCharacters: Set<Character> = [" ", ";", ".", "!", "/"] // 原地修改原字符串 string.removeCharacters(in: removeCharacters) print(string)
如果不需要修改原字符串,可以调用返回新实例的方法:
let rawString = "test/string! with space;" let cleanedString = rawString.removingCharacters(in: [" ", ";", ".", "!", "/"]) // cleanedString 结果为 "teststringwithspace",rawString 保持不变
- 额外优化提示:如果项目中有固定要移除的字符集合,可以额外封装便捷方法减少重复传参:
extension String { mutating func removeCommonSpecialCharacters() { self.removeCharacters(in: [" ", ";", ".", "!", "/"]) } }
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

