You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4(Xcode 9.2)中stringByTrimmingCharactersInSet弃用及报错咨询

解决Swift 4中stringByTrimmingCharactersInSet弃用的问题

这是Swift版本迭代里很常见的API调整,别慌——Swift 4把原来OC风格的字符串处理方法都重构得更贴合Swift的语法习惯了。

原来Swift 2里的stringByTrimmingCharactersInSet(_:)方法已经被废弃,取而代之的是String类型直接提供的trimmingCharacters(in:)实例方法,同时字符集的写法也做了简化:

原Swift 2代码:

let newString = title.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

替换后的Swift 4兼容代码:

let newString = title.trimmingCharacters(in: .whitespaces)

如果你的需求是同时去除空格、换行符这类全类型空白字符,还可以直接用预定义的字符集:

let newString = title.trimmingCharacters(in: .whitespacesAndNewlines)

简单来说就是把方法名简化,字符集用CharacterSet的静态属性即可——Swift 4里NSCharacterSet和CharacterSet已经无缝桥接,用.whitespaces这种写法更简洁直观。

内容的提问来源于stack exchange,提问作者Arunabh Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:15:28