Charlie Pico
Charlie Pico

Reputation: 2036

Ambiguous Reference: UITextField.text error Swift 3

So I've just updated to Xcode 8 and converted my Swift 2.3 code to Swift 3, and I have an error in this line of code that wasn't in Swift 2.3:

let holder:NSString! = NSString.init(string: moneyBar.text!).substring(with: NSRange.init(location: y, length: 1))

Now in Swift 2.3 the line has no error, but in Swift 3 it looks like the moneyBar.text! is marked with the error Ambiguous reference to member 'text'.

Is this a Swift 3 bug? Or I'm missing something?

Upvotes: 1

Views: 1343

Answers (2)

serg_zhd
serg_zhd

Reputation: 1043

You are accessing single character so consider using subscripts of String class.

let holder = text[text.index(text.startIndex, offsetBy: y)]

Here is an extension for convenience:

public extension String {

    func character(_ at: Int) -> Character {
        return self[self.index(self.startIndex, offsetBy: at)]
    }

    func substring(_ r: Range<Int>) -> String {
        let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
        let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
        return self.substring(with: Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex)))
    }

}

let text = "abc"
let holder1 = text.character(1) // b
let holder2 = text.substring(1..<2) // b

Upvotes: 0

Jim Matthews
Jim Matthews

Reputation: 1191

I think the syntax you want is:

let holder = NSString(string: moneyBar.text!).substring(with: NSRange(location: y, length: 1))

Upvotes: 1

Related Questions