Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i convert NSString to String

Tags:

swift

Im trying to convert a NSString from a text field to a standard String so that I can check if it contains a certain character.

I have tried

var nSStringText = textField.text! as NSString
var stringText = nSStringText as String

output

'NSString' is not convertible to 'String'
like image 213
Nic Wanavit Avatar asked Jun 10 '26 21:06

Nic Wanavit


2 Answers

let myNSString: NSString = "I'm iOSDev"
let myString: String = myNSString as String
print(myString)
print(myString.isEmpty)

Casting Refer to myNSString as String

Also, You don't need to cast textField text as NSString it's by default String So, Just use

var myString: String = myTextField.text ?? ""

I Couldn't comment so Posting as Answer

like image 191
Jatin Garg Avatar answered Jun 13 '26 16:06

Jatin Garg


NSString and String are bridged. You don't need to, and can't, cast from one to the other. As vacawama says in his comment, a UITextField's text property is already of types String.

like image 33
Duncan C Avatar answered Jun 13 '26 17:06

Duncan C