如何获取字符串的第n个字符?我try 了支架([])访问器,但没有成功.

var string = "Hello, world!"

var firstChar = string[0] // Throws error

错误:"下标"不可用:无法将字符串下标为Int,请参阅文档注释进行讨论

推荐答案

Attention:有关Swift 4和Swift 5的正确实施,请参见Leo Dabus' answer.

Swift 4或更高版本

Swift 4中引入了Substring型来制作子字符串

Try it out here

extension StringProtocol {
    subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] }
    subscript(range: Range<Int>) -> SubSequence {
        let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
        return self[startIndex..<index(startIndex, offsetBy: range.count)]
    }
    subscript(range: ClosedRange<Int>) -> SubSequence {
        let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
        return self[startIndex..<index(startIndex, offsetBy: range.count)]
    }
    subscript(range: PartialRangeFrom<Int>) -> SubSequence { self[index(startIndex, offsetBy: range.lowerBound)...] }
    subscript(range: PartialRangeThrough<Int>) -> SubSequence { self[...index(startIndex, offsetBy: range.upperBound)] }
    subscript(range: PartialRangeUpTo<Int>) -> SubSequence { self[..<index(startIndex, offsetBy: range.upperBound)] }
}

要将Substring转换为String,您只需

如果有人能想出一个合并的好方法,那就太好了


为什么这不是内置的?

错误信息显示为"see the documentation comment for discussion".苹果在文件UnavailableStringAPIs.swift中提供了以下解释:

无法使用整数订阅字符串.

"字符串中的第i个字符"的概念已经过时

Swift提供了几种不同的方式来访问角色

  • String.utf8是中的UTF-8代码单元的集合

  • String.utf16是UTF-16代码单元的集合

  • String.unicodeScalars是Unicode标量的集合.

  • String.characters是一个扩展字集

请注意,在处理包含人类可读文本的字符串时,

Swift相关问答推荐

JSON如何解码空对象

UITableView未显示类数组数据

动画过程中的SwiftUI重绘视图

如何在SWIFT中解码Instagram Backup中的字符串?

像WebSocket一样接收实时更新,但通过异步/等待或组合

如何让默认函数参数引用另一个函数参数?

Swift Combine:如何在保留发布者结果顺序的同时进行收集?

TextField 键入未完成

为 SwiftUI 中的属性提供默认值

如何在 SwiftUI 中获取视图的位置

Swift:创建用于调用 C 函数的指针数组

符合协议 - 错误?

如何在填充上添加 if else 语句? SwiftUI

找不到目标AAA的 SPM 工件 - 仅限 Xcode 13.3

macOS 守护进程应该由Command Line ToolXcode 模板制作吗?

'NSLog' 不可用:可变参数函数在 swift 中不可用

Swift 覆盖实例变量

为什么我可以转换为 NSManagedObject 但不能转换为我的实体类型?

是 swift 中另一个日期的同一周、月、年的日期

无法推断泛型参数的参数