1

I want to create a max length to my textfield with IBInspectable, I see a answer to this on a question here but I'm getting an error saying Expression type '()' is ambiguous without more context,

My code was

import UIKit

private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
               return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    @objc func fix(textField: UITextField) {
        let t = textField.text
        textField.text = t?.prefix(maxLength)
    }
}

and I'm getting an error pointing at textField.text = t?.prefix(maxLength) with an error message saying Expression type '()' is ambiguous without more context,

How can I resolve it?

Dylan
  • 1,121
  • 1
  • 13
  • 28

1 Answers1

2

In Swift 5, String's prefix method returns a value of type String.SubSequence

func prefix(_ maxLength: Int) -> Substring

You'll need to convert this to a String type.

One way to do this might be:

let s = textField.text!.prefix(maxLength) // though UITextField.text is defined as an optional String, can be safely force-unwrapped as the default value is an empty string even when set to nil
textField.text = String(s)

or if you prefer a single-line solution:

textField.text = String(textField.text!.prefix(maxLength))
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
dbn
  • 458
  • 5
  • 12
  • UITextField `text` property default value is an empty string. Keeping `t` optional is pointless – Leo Dabus Jun 03 '20 at 05:10
  • UITextField.text is defined as an optional String. I was just keeping inline with OP's original code. open var text: String? // default is nil – dbn Jun 03 '20 at 05:14
  • UITextField `text` property value will NEVER be nil – Leo Dabus Jun 03 '20 at 05:17
  • Thanks for keeping me honest. The "Jump to definition" action reveals what appears to be an outdated comment in the UITextField code. I'll edit the answer – dbn Jun 03 '20 at 05:31