1

I am studying Swift and creating a little app for college. I am using Alamofire and SwiftyJSON to work with my API.

Model Products

class Products {
    var id: Int {
        get {
            return self.id
        }
        set {
            self.id = newValue
        }
    }

    var name: String {
        get {
            return self.name
        }
        set {
            self.name = newValue
        }
    }

    var description: String {
        get {
            return self.description
        }
        set {
            self.description = newValue
        }
    }

    var price: String {
        get {
            return self.price
        }
        set {
            self.price = newValue
        }
    }

    init(id: Int, name: String, description: String, price: String) {
        self.id = id
        self.name = name
        self.description = description
        self.price = price
    }
}

My ViewController

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, Urls.menu).responseJSON { request in
            if let json = request.result.value {
                let data = JSON(json)

                for (_, subJson): (String, JSON) in data {
                    let product = Products(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].string!)
                }
            }
        }
    }
}

When I try to run my code, I receive an error in my Model Products, line 14:

Thread 1: EX_BAD_ACCESS (code=2, address=0x7fff5e961ff8)

In the setter of my property id.

I check my error log in xcode, and it shows that this setter is called more than 250 thousand times.

Can anyone know what I am doing wrong?

Thank you.

1 Answer 1

2

Your code causes an infinite loop because the explicit setter calls itself again and again.

In Swift properties are synthesized implicitly, just declaring them is sufficient.

class Products {
    var id: Int 
    var name: String
    var description: String 
    var price: String 

    init(id: Int, name: String, description: String, price: String) {
        self.id = id
        self.name = name
        self.description = description
        self.price = price
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.