Vlad Alexeev
Vlad Alexeev

Reputation: 2214

Value of "String" has no member 'indices' - moving to Swift 3.0

I'm moving from Swift 2 (probably, 2.3) to 3.0 and have a hard time correcting following code : Now, I know that String is not a collection anymore. How do I correct this particular code?

let separator = anyWord.indexOf("-")!

anyWord.substring(with: (anyWord.indices.suffix(from: anyWord.index(anyWord.startIndex, offsetBy: separator + 1))))

Upvotes: 0

Views: 772

Answers (2)

Hamish
Hamish

Reputation: 80951

As a possible improvement to @dfri's first solution, you could use the upperBound of String's range(of:) method (which is bridged from NSString) – which will give you the index after the (first occurrence of the) dash in your string.

import Foundation

let anyWord = "foo-bar"

if let separator = anyWord.range(of: "-")?.upperBound {
    let bar = anyWord.substring(from: separator)
    print(bar) // bar
}

Or even compacted into a crazy single binding using Optional's map(_:) method:

if let bar = (anyWord.range(of: "-")?.upperBound).map(anyWord.substring(from:)) {
    print(bar) // bar
}

Although note that the general solution to the problem of 'String not being a collection anymore', is to use string.characters instead, which is a Collection.

Upvotes: 2

dfrib
dfrib

Reputation: 73206

I'm slightly uncertain as to what you want to achieve, but it seems you'd like, for e.g. a string foo-bar, to construct a substring after a given separator, e.g. bar given foo-bar.

You could achieve this in less complicated fashions than the method you're attempting to implement.

E.g.

let anyWord = "foo-bar"

if let separator = anyWord.characters.index(of: "-") {
    let subStartIndex = anyWord.characters.index(after: separator)
    let bar = anyWord[subStartIndex..<anyWord.endIndex]
    print(bar) // bar
}

Or, as another alternative, use Collection's split(separator:maxSplits:omittingEmptySubsequences:) method applied to the .characters (collection):

let anyWord = "foo-bar"

if let chars = anyWord.characters
    .split(separator: Character("-"), maxSplits: 1)
    .dropFirst(1).last {
    let bar = String(chars)
    print(bar) // bar
}

Or, as another alternative, using the components(separatedBy: "-") method of String:

import Foundation

let anyWord = "foo-bar"

let bar = anyWord.components(separatedBy: "-").dropFirst(1).reduce("", +)
print(bar) // bar

Upvotes: 2

Related Questions