Arun Kumar P February 2016

'advance' keyword in swift?

let word = "sample string"

let firstLetter = Character(word.substringToIndex(advance(word.startIndex,1)).uppercaseString)

I got the above example from a tutorial. Can anyone know what they mean by "advance" and what is difference between "substringToIndex" and "substringWithRange".

Answers


Eric D. February 2016

This advance syntax is from Swift 1.

Now with Swift 2 it's written like this:

let firstLetter = Character(word.substringToIndex(word.startIndex.advancedBy(1)).uppercaseString)

The advance method moves the current index along the String.

With substringToIndex you slice a part of the String, beginning at the start of the String and ending at the index defined by advance.

Here you advance by 1 in the String, so it means that substringToIndex will get the first character from the String.


UlyssesR February 2016

substringToIndex

Returns a new string containing the characters of the receiver up to, but not including, the one at a given index.

Return Value A new string containing the characters of the receiver up to, but not including, the one at anIndex. If anIndex is equal to the length of the string, returns a copy of the receiver.

substringWithRange

Returns a string object containing the characters of the receiver that lie within a given range.

Return Value A string object containing the characters of the receiver that lie within aRange.

Special Considerations This method detects all invalid ranges (including those with negative lengths). For applications linked against OS X v10.6 and later, this error causes an exception; for applications linked against earlier releases, this error causes a warning, which is displayed just once per application execution.

For more info detail, you can get in the Apple NSString Class Reference


Code Different February 2016

Your tutorial is outdated. advance was deprecated in Swift 2. Strings in Swift cannot be randomly accessed, i.e. there's no word[0] to get the first letter of the string. Instead, you need an Index object to specify the position of the character. You create that index by starting with another index, usually the startIndex or endIndex of the string, then advance it to the character you want:

let word   = "sample string"
let index0 = word.startIndex                // the first letter, an 's'
let index6 = word.startIndex.advancedBy(6)  // the seventh letter, the whitespace

substringToIndex takes all characters from the left of string, stopping before the index you specified. These two are equivalent:

print("'\(word.substringToIndex(index6))'")
print("'\(word[index0..<index6])'")

Both print 'sample'

Post Status

Asked in February 2016
Viewed 1,374 times
Voted 4
Answered 3 times

Search




Leave an answer