Xcodeの9•スウィフト4
extension StringProtocol where Index == String.Index {
func nsRange(from range: Range<Index>) -> NSRange {
return NSRange(range, in: self)
}
}
let string = "Hello USA !!! Hello World !!!"
if let range = string.range(of: "Hello World") {
let nsRange = string.nsRange(from: range)
(string as NSString).substring(with: nsRange) // "Hello World"
}
ます。また、対応するnsRangeを作成することができます(以下のようStringProtocolを拡張:)方法の:
extension StringProtocol where Index == String.Index {
func nsRange<T: StringProtocol>(of string: T, options: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil) -> NSRange? {
guard let range = self.range(of: string, options: options, range: range ?? startIndex..<endIndex, locale: locale ?? .current) else { return nil }
return NSRange(range, in: self)
}
func nsRanges<T: StringProtocol>(of string: T, options: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil) -> [NSRange] {
var start = range?.lowerBound ?? startIndex
let end = range?.upperBound ?? endIndex
var ranges: [NSRange] = []
while start < end, let range = self.range(of: string, options: options, range: start..<end, locale: locale ?? .current) {
ranges.append(NSRange(range, in: self))
start = range.upperBound
}
return ranges
}
}
let string = "Hello USA !!! Hello World !!!"
if let nsRange = string.nsRange(of: "Hello World") {
(string as NSString).substring(with: nsRange) // "Hello World"
}
let nsRanges = string.nsRanges(of: "Hello")
print(nsRanges) // "[{0, 5}, {19, 5}]\n"
http://stackoverflow.com/a/30404532/1187415チェック変換スウィフト1.2、2のための方法、および3 –
を持って...とスウィフト4 –