0

New at Swift and playing around with optionals and how they work. Is there some reason you can't initialize an optional in a struct method? If you change 'A' to be a class then this all works. Using Xcode 6.3.1.

struct A {
    var myString: String?

    init () {
        // do something
    }

    func getData () {
        // This next line doesn't compile correctly
        //self.myString = "This is a test"
    }    
}

var a = A()
a.myString = "Test" // This line works
Markus Amalthea Magnuson
  • 8,415
  • 4
  • 41
  • 49
lizard88
  • 1
  • 1
  • 1
    This is not a problem of optionals. The reason is that a struct method which modifies properties must be marked as "mutating". – Lookup "Modifying Value Types from Within Instance Methods" in the Swift book! – Martin R Apr 30 '15 at 13:03
  • 1
    One must admit that the Swift error message could do a slightly better job of stating the issue. – matt Apr 30 '15 at 13:04

0 Answers0