3

I have this code in objective-c:

[textField.text stringByReplacingCharactersInRange:range withString:string];

try to convert to swift, like so:

textField.text.stringByReplacingCharactersInRange(range, withString: string)

but compiler says, Int is not identical to 'String.index'

How should I modify expression?

I am using both objective-c / swift expressions in UITextFieldDelegate method:

func textField(textField: UITextField!,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String!) -> Bool {

enter image description here

János
  • 32,867
  • 38
  • 193
  • 353
  • How are you defining `range`, in both cases? – Undo Jul 20 '14 at 14:12
  • Both have NSRange type – János Jul 20 '14 at 14:16
  • I get a different error message relating the range, and not the string, like on the other thread – János Jul 20 '14 at 14:21
  • 2
    The other thread is about the same problem (implementing `shouldChangeCharactersInRange`). Have you tried the solution (using `bridgeToObjectiveC`) ? That seems to work fine. Error messages might change between beta releases of the Swift compiler. – Martin R Jul 20 '14 at 14:33

1 Answers1

1

Use bridgeToObjectiveC()

textField.text.bridgeToObjectiveC().stringByReplacingCharactersInRange(range, withString: string)

it will more clarify

var st = "abc"
str.bridgeToObjectiveC().stringByReplacingCharactersInRange(NSMakeRange(2,1), withString:"r")

Explicit casting can also be done to NSString and it not needs bridgeToObjectiveC

var st = "abc" as NSString
let abc = st.stringByReplacingCharactersInRange(NSMakeRange(2, 3), withString: "abc")
codester
  • 36,891
  • 10
  • 74
  • 72