I have a string here, which I am trying to substring.
let desc = "Hello world. Hello World."
var stringRange = 1..<5
desc.substringWithRange(stringRange)
However Swift gives me an error with this. What have I done wrong? I am using the new notation of the stringRange because it doesn't let me use the old one.
The Range
you have created does not have the correct type, it is inferred to be an Int
. You need to create the range from the string itself:
let desc = "Hello world. Hello World."
let stringRange = desc.startIndex..<desc.startIndex.advancedBy(5)
let sub = desc[stringRange]
It's slightly more complex with String
. Alternatively, go back to NSString
and NSRange
:
let range = NSMakeRange(0, 5)
let sub2 = (desc as NSString).substringWithRange(range)
Your 1..<5
is from type Range<Int>
, while the method substringWithRange
expects a value from type Range<Index>
let desc = "Hello world. Hello World."
var dd = desc.substringWithRange(desc.startIndex..<desc.startIndex.advancedBy(5))
You may apply advanceBy
to the desc.startIndex
as well
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.