Dejan Skledar
Dejan Skledar

Reputation: 11435

How to convert NSString to Character in Swift?

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

Answers (3)

cmyr
cmyr

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

Martin R
Martin R

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

Mohsen
Mohsen

Reputation: 65785

Use Character class

var chars = [Character](str)

Upvotes: 13

Related Questions