MogaWine
MogaWine

Reputation: 5

Segmentation Fault in Swift Playground

I'm new here and I'm doing some exercise in Swift and I found this problem:

When I try to execute this code I get a Segmentation Fault and I can't figure out why.

class Persona{
  private var nome:String?
  private var cognome:String?
  private var eta:Int?

  public var Sesso:String{
      get{
            return Sesso
        }
        set{
            if newValue=="M" || newValue == "m" {
                Sesso="Maschio"
            }
            else{
                Sesso="Femmina"
            }
        }
    }
    init(nome:String, cognome:String, eta:Int)
    {
        self.nome=nome
        self.cognome=cognome
        self.eta=eta
    }
    init(){}
    func getNome()->String{ return nome! }
    func getCognome()->String{ return cognome! }
    func getEta()->Int{ return eta! }

    func setNome(nome:String)->(){ self.nome=nome }
    func setCognome(cognome:String)->(){ self.cognome=cognome }
    func setEta(eta:Int)->(){ self.eta=eta }

} 
var p1 = Persona(nome:"AAAA",cognome:"BBBB",eta:22)
p1.Sesso = "M"
p1.setEta(eta:44)
print("\(p1.getNome()) \t \(p1.getCognome()) \t \(p1.getEta()) \t \(p1.Sesso)")
p1.setEta(eta:22)

Upvotes: 0

Views: 71

Answers (2)

luk2302
luk2302

Reputation: 57114

You are basically trying to use a computed property

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

The key here is "which do not actually store a value". That can be seen clearer when you try to use the getter since print(p1.Sesso) causes a crash as well since you end up in an infinite loop of the getter calling itself over and over again. What you should do is define the computed property but at the same time define another stored property which actually holds the data:

private var _sesso:String = ""
public var Sesso:String{
    get{
        return _sesso
    }
    set{
        if newValue=="M" || newValue == "m" {
            _sesso="Maschio"
        }
        else{
            _sesso="Femmina"
        }
    }
}

Upvotes: 1

Agent Smith
Agent Smith

Reputation: 2913

The Problem is you can't access a variable in its own getter and setter.

Instead you can use didSet

public var Sesso : String{
    didSet {
        if Sesso == "M" || Sesso == "m" {
            Sesso = "Maschio"
        }
        else{
            Sesso = "Femmina"
        }
    }
}

and you can know more about getters and setters from this answer and can also check apple documentation on Properties for more clarification.

Upvotes: 0

Related Questions