0

I want to assign the first char of a string. Of course there is a advance function, but to me (I come from C++) it is much easier to read when simply using [index]. So I defined an extension for String type:

extension String {

    subscript (i: Int) -> Character {
        return self[advance(self.startIndex, i)]
    }

    subscript (i: Int) -> String {
        return String(self[i] as Character)
    }

    ...

This works fine for a condition like:

if (s[0] == "u") 

but when assigning this value like

var c = s[0]

I get an error that compiler can't subscript String with type of int. But where is the difference?

Peter71
  • 2,180
  • 4
  • 20
  • 33

1 Answers1

2

I think the compiler cannot infer the return type of subscript, since these two subscript have the same input signature.

So you have to specify which subscript you want to use. Like this,

var c:Character = s[0]

or

var c:String = s[0]
nRewik
  • 8,958
  • 4
  • 23
  • 30
  • YES! You are right. Now it's clear. The comparison adds the type needed from the constant string. Thank you very much! – Peter71 Jul 14 '15 at 09:26