所以我仍在使用Swift3,但收到了我在NSRange and Swift使用的片段的编译器警告,我不明白,特别是这个函数:
/// Returns a substring with the given `NSRange`,
/// or `nil` if the range can't be converted.
func substring(with nsrange: NSRange) -> String? {
guard let range = nsrange.toRange()
else { return nil }
let start = UTF16Index(range.lowerBound)
let end = UTF16Index(range.upperBound)
return String(utf16[start..<end])
}
Xcode 9抱怨:范围提取'init'已被弃用。我认为类型别名 - UTF16Index,用法是问题,但没有全部解决这个问题,我想尝试理解和解决。
答案 0 :(得分:0)
是的,问题是duplicate部分;不确定我提供的那个或参考是否是原始来源;无论如何,使用这个答案作为指导 - 但仍然试图理解它,我想出了这个。
extension String {
/// An `NSRange` that represents the full range of the string.
var nsrange: NSRange {
return NSRange(location: 0, length: utf16.count)
}
/// Returns a substring with the given `NSRange`,
/// or `nil` if the range can't be converted.
func substring(with nsrange: NSRange) -> String? {
guard let range = Range(nsrange, in: self) else { return nil }
return self[range]
}
/// Returns a range equivalent to the given `NSRange`,
/// or `nil` if the range can't be converted.
func range(from nsrange: NSRange) -> Range<Index>? {
guard let range = Range(nsrange, in: self) else { return nil }
return range
}
}