user2976267 user2976267 - 6 months ago 122
Swift Question

String and index in Swift 3

here's a part of my code :

let separator = anyWord.indexOf("-")!
if (separator >= 0) {
let res = anyWord[anyWord.characters.index(after: separator)..<anyWord.endIndex] //get an error
//some code

I get an error in 'let res' part - Type 'String!' has no subscript members

if I do :

let separator = anyWord.indexOf("-")!
let subStartIndex = anyWord.characters.index(after: separator)

the extension to String :

extension String {
public func indexOf(_ char: Character) -> Int! {
if let idx = self.characters.index(of: char) {
return self.characters.distance(from: self.startIndex, to: idx)
return Const.INVALID_VALUE

I get error :

String may not be indexed with 'Int", it has variable size elements


You are thinking too complicated, it's pretty easy in Swift 3 using range(of and upperBound

let anyWord = "asdghf-fkgjh"
if let separator = anyWord.range(of:"-") {
   let res = anyWord.substring(from: separator.upperBound)
   //some code