1

I got a crash when i try to set a variable inside a extension:

extension String {
 var index: Int {
    get {
        return self.index
    }
    set {
        self.index = newValue
    }
 }
}

var o: String = "tre"


o.index = 87 // crash here
println(o.index) // Even here

i tried everything, without any success. Thanks in advance for your help.

user2724028
  • 594
  • 2
  • 8
  • 19
  • 1
    Just wondering, in what manner does `index` have anything to do with `String`? IOW, what are you trying to accomplish? – zaph Oct 10 '14 at 13:53
  • I wanted to add a new property named index or whatever, in the String class. It sounds like impossible. It doesn't matter thanks anyway. – user2724028 Oct 10 '14 at 14:02
  • Please do not add an extension method to a class unless from the name alone it is easily understood what it does. `String` is a particularly bad place to ass `index` since they may contain variable length characters. – zaph Oct 10 '14 at 14:11
  • In fact the sample code was an example, in fact i wanted to add a Int inside a UIViewController extension, but i had the same issue. – user2724028 Oct 10 '14 at 14:14
  • In the case of `UIViewController` just create a subclass. – zaph Oct 10 '14 at 15:47

2 Answers2

0

You are making a loop by infinitely setting or getting a property.

You cannot add new stored properties with extension, only computed ones that are not backed by a property.

Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • Don't know why there is no compiler errors/warnings for this, but you could do the same in Objective-C if setting/getting property inside setter/getter of it without using instance variable directly. – Kirsteins Oct 10 '14 at 14:08
  • 1
    There is no compiler error because he hasn't declared a stored property, only a computed one that refers to itself. – JeremyP Oct 10 '14 at 15:31
0

You cannot add new stored variables to a type using extensions.

fluidsonic
  • 4,655
  • 2
  • 24
  • 34