Swift中如何构造AttributedString.Index解决类型转换错误?
如何构造AttributedString.Index来使用insert方法?
在Swift里,AttributedString的索引不能直接用整数(Int)传入,你需要借助它的集合特性来生成合法的AttributedString.Index。
解决这个问题的关键是利用AttributedString遵循的Collection协议提供的index(_:offsetBy:)方法——以起始索引(startIndex)为基准,偏移指定位数就能得到目标位置的索引。
修改后的代码如下:
func setFooterMessage() -> AttributedString { var mOne = AttributedString("Play Monday") mOne.foregroundColor = .white let mTwo = AttributedString("on") // 从起始索引偏移6位,生成合法的AttributedString.Index let insertIndex = mOne.index(mOne.startIndex, offsetBy: 6) mOne.insert(mTwo, at: insertIndex) return mOne }
额外说明:这种索引方式是Swift集合类型(包括String、AttributedString)的标准用法,能避免因复杂字符(比如表情符号、多字节组合字符)导致的位置计算偏差,保证插入位置的精准性。
内容的提问来源于stack exchange,提问作者Christopher
相关产品推荐
相关产品推荐

