0

I have a task to do something with a chess board. The input gives us a starting position of some chess figure. For example "b4" or "a6" or something like that. How can i decompose the input and make from it two integer numbers, like in C++:

string input;
cin>>input

int coord_x = input[0] - 'a';

int coord_y = input[1]

I cannot manage to do that in swift. I do something like:

let input : String=readLine()!
let characters = Array(input)

and then try to take the int but it doesnt work, no matter what i try... and what type is the content of the Array in swift?

0

1 Answer 1

1

You can retrieve the c string representation like this:

let string = "a5"
let scalars = string.lowercased().cString(using: .ascii)!

let first = scalars[0]
let second = scalars[1]

It could be safer to retrieve the unicodeScalar characters instead:

let string = "a5".lowercased()
let characters = Array(string.unicodeScalars)

let first = characters[0].value - UnicodeScalar(unicodeScalarLiteral: "a").value
Sign up to request clarification or add additional context in comments.

1 Comment

Int8 is always representable to Int(64), just convert with Int(first).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.