Skip to content
Tom Ryan edited this page Jun 2, 2015 · 2 revisions

Structs are Value Types

struct TutorialStruct {
    var firstVariable : Int

    init(firstVariable : Int) {
        self.firstVariable = firstVariable
    }

    mutating func changeFirstVariable(newVal : Int) {
        self.firstVariable = newVal
    }
}

func ==(lhs: TutorialStruct, rhs: TutorialStruct) -> Bool {
    return lhs.firstVariable == rhs.firstVariable
}

When copying a struct, the copy is just that: a copy.

var structTest = TutorialStruct(firstVariable: 0)
var secondStructTest = structTest
println(structTest.firstVariable) // 0
println(secondStructTest.firstVariable) // 0

secondStructTest.firstVariable = 2
println(structTest.firstVariable) // 0
println(secondStructTest.firstVariable) // 2
  • Note that structTest.firstVariable's value remains 0, while secondStructTest.firstVariable has been changed to 2