8

I'm not sure what I'm missing here, but all I'm trying to do is get a substring from a string. I'm messing around in a playground, and my code is only three lines long lines long, I declare a string, get an index, then try and get a substring from it, and I get this error. This is all I have for my code...

var name = "Stephen"
var index = name.startIndex.advancedBy(3)
var substring = name.substringToIndex(index)

Am I doing this wrong? I don't see any other ways to get a substring from a string.

In an unrelated question, if I want to grab a substring from a string between indices 2 and 5 how would I go about that in Swift 2?

Bill L
  • 2,576
  • 4
  • 28
  • 55

3 Answers3

14

For anyone who is searching for Swift 3 solution:

var name = "Stephen"
var index = name.index(name.startIndex, offsetBy:3)
var substring = name.substring(to:index)
carmine
  • 1,597
  • 2
  • 24
  • 33
12

Since substringToIndex is defined into the Foundation module, you need to add

import Foundation

enter image description here

enter image description here

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
0

about the unrelated question..

var name = "Stephen"
var substring = name.substringWithRange(Range<String.Index>(start: name.startIndex.advancedBy(3),end: name.startIndex.advancedBy(5)))

related answer link

Community
  • 1
  • 1
TomCobo
  • 2,886
  • 3
  • 25
  • 43