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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:08:09