Stryng
旨在通过使用常见且易于记忆的下标语法,以及使用 Int
索引访问字符和范围,使字符串操作更加容易。
Swift 的字符串管理是该语言最令人头疼的特性之一。 当然,拥有 Unicode 正确性和效率是件好事,但这是有代价的:过于冗长和复杂。
检索特定位置的单个字符。
let string = "Example"
// With Stryng
string[1] // "x"
// Without
string[string.index(string.startIndex, offsetBy: 1)] // "x"
检索到特定索引的子字符串。
let string = "Example"
// With Stryng
string[..<2] // "Ex"
// Without
string[..<string.index(string.startIndex, offsetBy: 2)] // "Ex"
检索两个索引之间的子字符串。
let string = "Example"
// With Stryng
string[1..<6] // "xampl"
// Without
string[string.index(string.startIndex, offsetBy: 1)..<string.index(string.startIndex, offsetBy: 6)] // "Ex"
检索所有子字符串出现的位置。
let string = "Example Example"
let occurences = string["xa"] // Returns a [Range<String.Index>] containing all positions of the subtring.
将 Substring
转换为 String
。
let example = "Example"
example[1...5].string // Returns a `String?` instead of a `Substring?`
这是一个最新的支持的下标列表。 如果您想查看更多实际的代码示例,请查看 StryngTests.swift
。
// String[1]
public subscript(index: Int) -> Character?
// String[0..<1]
public subscript(range: Range<Int>) -> Substring?
// String[0...1]
public subscript(range: ClosedRange<Int>) -> Substring?
// String[..<1]
public subscript(value: PartialRangeUpTo<Int>) -> Substring?
// String[...1]
public subscript(value: PartialRangeThrough<Int>) -> Substring?
// String[1...]
public subscript(value: PartialRangeFrom<Int>) -> Substring?
// String["substring"]
public subscript(string: String) -> [Range<String.Index>]
// String["begin"..."end"]
public subscript(range: ClosedRange<String>) -> [ClosedRange<String.Index>]
// String["begin"..<"end"]
public subscript(range: Range<String>) -> [Range<String.Index>]
// String[Character("a")]
public subscript(character: Character) -> [String.Index]
// String["begin"...]
public subscript(range: PartialRangeFrom<String>) -> PartialRangeFrom<String.Index>?
// String[..."end"]
public subscript(range: PartialRangeThrough<String>) -> PartialRangeThrough<String.Index>?
要通过 Cocoapods 安装,请将以下行添加到您的 Podfile 中
pod 'Stryng'
要通过 Swift Package Manager 安装,请将以下行添加到您的 Package.swift
文件中的 dependencies
数组中
.package(url: "https://github.com/BalestraPatrick/Stryng.git", from: "0.4.1")
然后,仍然在您的 Package.swift
中,将 "Stryng"
添加到您 *target* 的 dependencies
数组中。
最后,在您的终端中,运行以下命令以更新您的依赖项
$ swift package update
是的,在 Swift 中遍历字符串可能很慢。 这些下标在标准库中不存在的原因是,有些人认为它隐藏了遍历字符串的性能影响。 从 startIndex
到 endIndex
遍历字符串的复杂度为 O(n)。 如果您需要获取特定索引处的字符,无论如何您都必须遍历字符串,但如果您知道自己在做什么,为什么需要 3 行代码而不是 1 行代码来执行此操作呢?
这就是 Stryng 存在的意义所在。
我们非常欢迎您的帮助。 请访问 issues 提供您的反馈。 如果您打开一个 Pull request,其中包含一个失败的测试用例(针对错误或新功能),将获得额外奖励! ⭐️
我是 Patrick Balestra。
电子邮件: me@patrickbalestra.com
Twitter: @BalestraPatrick。
Stryng
在 MIT 许可下可用。 有关更多信息,请参阅 LICENSE 文件。