简体   繁体   中英

how to use a property from a class to another class in swift

I have a model class like this

import Foundation
import SwiftyJSON

class SpecificCategoryJSON {

var _product_id: Int?
var _product_title: String?
var _product_sku: String?
var _product_image: URL?

init(items: JSON){

    self._product_id = items["product_id"].int
    self._product_title = items["product_title"].stringValue
    self._product_sku = items["product_sku"].stringValue
    let post_imgAA = items["product_image"].arrayValue
    for itemsIMG in post_imgAA {
        self._product_image = itemsIMG["guid"].URL
    }

}
var product_id: Int {
    if _product_id == nil {
        _product_id = 0
    }
    return _product_id!
}

var product_title: String {
    if _product_title == nil {
        _product_title = ""
    }
    return _product_title!
}

var product_sku: String {
    if _product_sku == nil {
        _product_sku = ""
    }
    return _product_sku!
}

var product_image: URL {
    if _product_image == nil {
        let myURL = "http://www.clker.com/cliparts/d/L/P/X/z/i/no-image-icon-hi.png"
        let noImage: URL = URL(string: myURL)!
        _product_image = noImage
    }
    return _product_image!
   }

  }

I want to use the product_id to send as a parameter to make a POST request using Alamofire . Here is the POST request where I have kept the product_id static .

    class ProductDetailsManager {

    //........
    func printPublicGists() -> Void {

    let url: String = "http://xxx/get_product_informations/"
    let parameter = ["product_id": 33]

    Alamofire.request(url, method: .post, parameters: parameter, encoding: URLEncoding.default, headers: nil)
     .responseJSON { (response) in

        guard response.result.error == nil else {
           print(response.result.error!)
           return
        }

        guard let value = response.result.value else {
            print("no product to show")
            return
        }

        print(value)

    }

   }
//.......
}

I want to get the product_id from the class SpecificCategoryJSON and use it in class ProductDetailsManager to make a call . What should I do , inherit ? override ? UserDefaults.standard.set ? Please help .

Maybe I misunderstood the question, but you should instantiate your SpecificCategoryJSON class and access it's property :

func printPublicGists() -> Void {
    let url: String = "http://xxx/get_product_informations/"    
    let cat = SpecificCategoryJSON(items: someJSON)

    let parameter = ["product_id": cat.product_id]

    // ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM