2017-08-05 113 views
0

Apple's Swift documentation for String.UTF16View说:NSRange.toRange()有什么意义?

使用NSRange类型的toRange方法[一个NSRange]实例转换Int值的可选范围。

NSRange类型的toRange方法有什么意义?而且,它为什么会返回nil

为什么不直接使用NSRangelocation得到lowerBoundNSMaxRange(_:)得到upperBound

例如,给定

let nsrange = NSRange(location: 3, length: 12) 

,而不是

let r = nsrange.toRange() 

为什么不只是做

let lowerBound = nsrange.location 
let upperBound = NSMaxRange(nsrange) 

回答

1

the Swift source code for the NSRange type’s toRange method implementation

public func toRange() -> Range<Int>? { 
    if location == NSNotFound { return nil } 
    return location..<(location+length) 
} 

当你怀疑,该方法使用NSRangelocation得到lowerBoundlocation+length,这相当于NSMaxRange(_:),得到upperBound。如果NSRangelocationNSNotFound,则返回nil

注意:从Swift 4开始,此方法已被弃用,并已重命名为Range.init(_:)