Megan
Megan

Reputation: 514

SWIFT 3 - Convert Integer to Character

I am trying to get something to look like this:

  1 2 3 4 5 6 7 8 9 10 
A * * * * * * * * * * 
B * * * * * * * * * * 
....until J

How do I convert row's value to a character Also I was thinking of using col and adding it to 64 for the ASCII value or adding it to 41 for the unicode character. I really don't care which way.

Would anyone know how I could do this???

    for row in 0..<board.count
    {
        for col in 0..<board[row].count
        {

            if row == 0 && col != 0
            {
                board[row][col] = ROW AS CHARACTER
            }
            else if col == 0 && row != 0
            {
                board[row][col] = A - J
            }
            else if(col != 0 && row != 0)
            {
                board[row][col] = "*"
            }
        }
    }

Upvotes: 1

Views: 1445

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236315

You can extend Int to return the desired associated character as follow:

extension Int {
    var associatedCharacter: Character? {
        guard 1...10 ~= self, let unicodeScalar = UnicodeScalar(64 + self) else { return nil }
        return Character(unicodeScalar)
    }
}



1.associatedCharacter    // A
2.associatedCharacter    // B
3.associatedCharacter    // C
10.associatedCharacter   // J
11.associatedCharacter   // nil

Upvotes: 2

user6451264
user6451264

Reputation:

(Un)fortunately, Swift tries very hard to separate the concept of a “character”, what you read on screen, and the underlying ASCII representation, for reasons which become very important when you deal with complex texts. (What letter comes after “a”? Depends what language you speak.)

Most likely, what you want is to increment the UnicodeScalar value which for “regular” text corresponds to the ASCII encoding.

let first = UnicodeScalar("A").value
board[row][col] = String(Character(UnicodeScalar(first + UInt32(row))!))

The extra steps and optional unwrapping is Swift’s way of reminding you of all the things that could go wrong when you “increment” a letter.

Upvotes: 0

Related Questions