-1

I use swift and what i want to do is to check this:

if string.characterAtIndex(i) == "a"

But i get error. How to convert this "a" so that can be same type with characters i loop.
Thanks.

Shubham Bhave
  • 383
  • 6
  • 17
Nik
  • 1,517
  • 5
  • 14
  • 19
  • *"But i get error."* What error, do we have to guess? How is `string` defined? Please show a (small) self-contained example and the exact error message. – Martin R Apr 09 '15 at 13:02
  • And have a look at [Get nth character of a string in Swift programming language](http://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language), which is probably what you are looking for. – Martin R Apr 09 '15 at 13:02
  • 1
    What about reading the error message, figuring out what it says, and changing your code accordingly? – gnasher729 Apr 09 '15 at 13:03
  • n.p I got it. All i need to do is if wmi.characterAtIndex(i) == String("a").utf16[0] – Nik Apr 09 '15 at 13:08

3 Answers3

1

You need to convert you UniChar - characterAtIndex(i) to a Character, so you can compare them.

Solution:

let ithChar:Character = Character(UnicodeScalar(string.characterAtIndex(i)))

if ithCahr == "a"
{
    //do some stuff

}

Hope it helps!

Dejan Skledar
  • 11,280
  • 7
  • 44
  • 70
1

Here is another way you could do it:

if string.characterAtIndex(i) == "a".characterAtIndex(0)
vacawama
  • 150,663
  • 30
  • 266
  • 294
0

In better explanatory way, this can be one of the ways to perform what you intend to do.

var str = "Hello, playground"
var newString = str as NSString    

var num:Int = countElements(str)

for var i = 0; i < num; i++
{
    if (  Array(str)[i] == "p") {
        println(Array(str)[i]) // will show the output 

        println("success");
        break;
    }
}
Keshav
  • 1,123
  • 1
  • 18
  • 36