如果我有以下内容:
let nsRange = NSRange(location: 5, length: 10)
var attributedString = AttributedString("This is some string that I want to attribute.")
// To attribute a substring I must first convert the range
let start = attributedString.index(attributedString.startIndex, offsetByUnicodeScalars: nsRange.location)
let end = attributedString.index(start, offsetByUnicodeScalars: nsRange.length)
// Now we have a Range<AttributedString.Index>
let range = start..<end
attributedString[range].foregroundColor = .red
^此代码有效^
但是如果我试图通过创建一个下标来删除一些样板文件,如下所示:
extension AttributedString {
subscript(_ range: NSRange) -> AttributedSubstring {
get {
let start = index(startIndex, offsetByUnicodeScalars: range.location)
let end = index(start, offsetByUnicodeScalars: range.length)
return self[start..<end]
}
}
}
attributedString[nsRange].foregroundColor = .red
^这行不通^
我得到一个Cannot assign through subscript: subscript is get-only
错误。但我不明白为什么。attributedString[nsRange]
返回一个AttributedSubstring
,AttributedSubstring
可以使用.foregroundColor = .red
语法设置属性。它适用于Range<AttributedString.Index>
,如str[start..<end].foregroundColor = .red
,所以为什么不与我的下标?
AttributedString
和AttributedSubstring
是结构体。值类型
let range = start..
attributedString[range]。foregroundColor = .red
不起作用。只有当上面的声明是var attributedString
- variable,而不是let attributedString
- constant时,这才有效。
let substring = attributedString[nsRange]
substring。foregroundColor =r
不起作用。这只适用于var substring
- variable
现在和
attributedString[nsRange].foregroundColor = .red
这不起作用,因为下标的内联返回是常量,与let
您只为下标编写了一个getter。如果你想通过它来写(如错误说明),你还需要一个setter:
set {
let start = index(startIndex, offsetByUnicodeScalars: range.location)
let end = index(start, offsetByUnicodeScalars: range.length)
self[start..<end] = newValue
}
aspi的观点是返回的结构体是一个副本(这在你从文档中给出的例子中也是正确的)。这些例子非常不同:
// This modifies a *copy* of `value`. It does *not* modify `xs`.
// It calls the subscript getter of `xs`.
var value = xs[i]
value.prop = "newThing"
// This modifies `xs`:
// It calls the subscript setter of `xs`.
xs[i].prop = "newThing"