let nsString = NSString("Some string")
let nsRange = NSRange(5...10)
type(of: nsString.substring(with: nsRange))
// => String.Type
How can I do this, but returning an NSString
instead of a String
. I'm not looking for a solution that uses Range<String.Index>
, I'm aware how to do it that way, but for what i'm doing the speed difference is noticeable. I'd like to keep things in the NSString
world.
EDIT: Why does a question like this get downvoted? It's a very clear question. I've explained my goal, and given a code example.
Benchmark code:
// time computation
func tc(computation: () -> Void) {
let startTime = DispatchTime.now()
for _ in 0..<100 {
computation()
}
let endTime = DispatchTime.now()
let ns = (endTime.uptimeNanoseconds - startTime.uptimeNanoseconds)
print("Time: \(ns)")
}
let string = String(repeating: "This is it. ", count: 10000)
let s1 = 19000
let s2 = 19020
tc {
let start = string.index(string.startIndex, offsetBy: s1)
let end = string.index(string.startIndex, offsetBy: s2)
string[start..<end]
}
tc {
(string as NSString).substring(with: NSRange(s1..<s2))
}
CodePudding user response:
Can't you cast NSString to String and vice versa?
let string = NSString("nsString") as String
let nsString = String("string") as NSString
CodePudding user response:
These are being done 100 times, Right?
let start = string.index(string.startIndex, offsetBy: s1)
let end = string.index(string.startIndex, offsetBy: s2)
How about doing this instead:
let start = string.index(string.startIndex, offsetBy: s1)
let end = string.index(string.startIndex, offsetBy: s2)
tc {
string[start..<end]
}
Which one is more optimized now?