简体   繁体   中英

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] = "*"
            }
        }
    }

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

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM