I am trying to get first char from String. It should be easy but I can't do in Swift 2.0 (with Xcode beta 6).
Get nth character of a string in Swift programming language
I have tried that method also. It use extension but I can't retrieve using that method. May I know how to do?
Two solutions without casting to NSString
let string = "Hello"
let firstChar1 = string.substringToIndex(string.startIndex.successor())
let firstChar2 = string.characters.first
Update for Swift 2:
Since Swift 2 returns Character
rather than String
a new String
must be created.
let firstChar2 = String(string.characters.first!)
Update for Swift 3:
successor()
has been replaced with index(after:..)
let firstChar1 = string.substring(to:string.index(after: string.startIndex))
Try this,
let str = "hogehoge"
let text = (str as NSString).substringFromIndex(1) // "ogehoge"
For what it's worth (and for people searching for and finding this topic), without casting the String to NSString, you need to do the following with Swift 2.1:
let myString = "Example String"
let mySubString = myString.substringWithRange(Range<String.Index>(start: myString.startIndex.advanceBy(0), end: myString.startIndex.advanceBy(4)))
print(mySubString) //'Exam'
This would printout "Exam". Must say that it's much more verbose than in Obj-C. And that's saying something... ;-) But it gets the job done and without casting to NSString.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With