Swift报错'subscript(_:)'不可用:无法用Int下标String如何解决?
报错原因
'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead 报错的核心原因是Swift的String类型原生不支持直接传入Int整数作为下标取值。Swift的String由可变长度的Unicode字符组成,必须使用专用的String.Index类型索引才能定位字符位置。
解决方案
方案1:直接修改报错行代码
不需要改动其他逻辑,仅需把你用到整数下标的位置做一次索引转换即可:
let textRange = UETextRange(charIndex: i, length: l - i) for j in textRange.charIndex...getCharIndexAfterEndOfRange(range: textRange) { // 新增索引转换逻辑 let targetIndex = initialText.index(initialText.startIndex, offsetBy: j - 1) if initialText[targetIndex] == "\n" { hits += 1 let hitIndex = attributeRange.index + (hits - 1) if hitIndex <= paragraphStyles.count { let charIndex = paragraphStyles[hitIndex].charIndex } } }
方案2:扩展String支持Int下标(适合频繁使用的场景)
如果你项目里很多地方都需要用整数取String的字符,可以给String加扩展封装索引转换逻辑,后续不用每次都重复写转换代码:
// 全局添加一次扩展即可 extension String { subscript(_ offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] } // 可选安全下标,偏移越界返回nil不会崩溃 subscript(safe offset: Int) -> Character? { guard offset >= 0, offset < count else { return nil } return self[index(startIndex, offsetBy: offset)] } }
添加扩展后你原来的代码不需要做任何修改就可以正常运行。
注意事项
- 直接使用普通下标的时候要确保偏移量不会小于0或者大于等于字符串的
count属性,否则会触发运行时崩溃 - 如果无法确定偏移量是否合法,优先使用安全下标
[safe:]
内容的提问来源于stack exchange,提问作者sdev dev
相关产品推荐
相关产品推荐

