Reputation: 11435
I want to convert NSString to Character in Swift.
I am getting a String from NSTextField, where I input a single character (Example "@"), I need this in Character type.
Upvotes: 7
Views: 16423
Reputation: 2265
this should be as simple as let characterFromString = Character(textField.text)
.
NSString
is automatically bridged to Swift's String
, and the Character
class has an init which accepts a single character String
; see the documentation here.
This requires that the input string contain a single grapheme cluster (i.e. a single character) and so you might want to validate your input before casting. A slightly more verbose version of the above would be:
let text = textField.text as String
if countElements(text) == 1 {
let character = Character(text)
// do what you want
} else {
// bad input :-(
}
Upvotes: 12
Reputation: 539695
The stringValue
of NSTextField
actually returns a Swift string and not NSString
:
let str = myTextField.stringValue // str is a String
You get the first element with
let ch = str[str.startIndex] // ch is a Character
A NSString
would have to be converted to a Swift string first:
let nsString : NSString = "@"
let str = String(nsString)
let ch = str[str.startIndex]
Upvotes: 1