Jeff
Jeff

Reputation: 539

Swift - Getter and Setter for Computed Properties as String type

Hello im really new to Swift development with no Objective-C background, although I have a strong fundamentals in java, swift has a very stiff learning curve for me, well I'll go straight to my question, but ill post the code first

 class Vehicle {

    var gear : String {

        get {
            return self.gear
        }

        set {
            self.gear = newValue
        }
    }
}

var vehicle = Vehicle()
vehicle.gear = "ADASD"

im having a compiler error saying

./run-swift: line 18: 30295 Segmentation fault: 11  gtimeout -k $TIMEOUT_KILL_AFTER $TIMEOUT_DURATION $SWIFT_COMPILER -target $TARGET -sdk $SDK $OPTIMIZATION_LEVEL $INPUT_FILE -o $OUTPUT_FILE

i realy dont understand as why this simple code does not compile using a String type, if I change the variable declaration as Int type and assign a value to its property i have no problems at all.

Upvotes: 0

Views: 3495

Answers (2)

dispute
dispute

Reputation: 1454

some addition to Rob's answer:

computed property is just the front door for some backing stored variables, in your case, the right way is declaring stored variables first, and using computed property's get set method to access it

class Vehicle {
    private var _gear : String = ""
    var gear : String {
        get {
            return _gear
        }
        set {
            _gear = newValue
        }
    }
}
var vehicle = Vehicle()
vehicle.gear = "ADASD"

the reason it not crash when declared as Int in the first place is it's not running enough time to make it overflow, I tried it and it take me a while to got this error enter image description here

Upvotes: 1

Rob Napier
Rob Napier

Reputation: 299275

self.gear here calls the getter for gear which calls self.gear. You've created an infinite loop. You have a similar situation for the setter. You don't need to implement get and set if you just want to store a property.

final class Vehicle {
    var gear : String
}

var vehicle = Vehicle()
vehicle.gear = "ADASD"

Upvotes: 3

Related Questions