user578386
user578386

Reputation: 1061

Value of type 'String' has no member indices

I am trying to migrate my Swift 2.2 code to Swift 3(beta) and I am getting the following error in the below code after migrating to Swift 3.0 ,"Value of type 'String' has no member indices"

Would require help on the following were routePathComponent is a String.

After Migrating

if routePathComponent.hasPrefix(":") {
   let variableKey = routePathComponent.substring(with: routePathComponent.indices.suffix(from: routePathComponent.characters.index(routePathComponent.startIndex, offsetBy: 1)))
}

Before Migrating

if routePathComponent.hasPrefix(":") {
                            let variableKey = routePathComponent.substringWithRange(routePathComponent.startIndex.advancedBy(1)..<routePathComponent.endIndex)
                            let variableValue = component.URLDecodedString()
                            if variableKey.characters.count > 0 && variableValue.characters.count > 0 {
                                variables[variableKey] = variableValue
                            }
                        }

Upvotes: 1

Views: 2437

Answers (4)

vadian
vadian

Reputation: 285069

If you want to omit the first character if it's a colon, that's the Swift 3 way

if routePathComponent.hasPrefix(":") {
  let variableKey = routePathComponent.substring(from: routePathComponent.index(after :routePathComponent.startIndex))
}

The equivalent of your other example in the comment is

if let endingQuoteRange = clazz.range(of:"\"") {
   clazz.removeSubrange(endingQuoteRange.upperBound..<clazz.endIndex)
   ...
}

Upvotes: 1

Nirav D
Nirav D

Reputation: 72410

You can use dropFirst() if you want just drop first character from String.

if routePathComponent.hasPrefix(":") {
    let variableKey = String(routePathComponent.characters.dropFirst())
}

Upvotes: 1

Nyakiba
Nyakiba

Reputation: 862

var routePathComponent = ":Hello playground"


if routePathComponent.hasPrefix(":") {
    let variableKey = routePathComponent.substringFromIndex(routePathComponent.startIndex.advancedBy(1))
    //print(variableKey)
}

This should do the trick

Upvotes: 0

user28434&#39;mstep
user28434&#39;mstep

Reputation: 6600

indices is property of Collection types. String is not Collection since v.2.3.

Use .characters property, which returns Collection of characters of the String.

Upvotes: 0

Related Questions