swift函数返回多个值

时间:2017-06-06 01:48:33

标签: ios swift function

下面是我尝试创建的一个函数,它将根据输入的键值获取JSON数据中的值。我遇到的问题是我需要能够在另一个计算中使用所有费率。我不确定如何将每个速率保存到全局变量。此时,该函数给出了一个错误 - “函数中缺少返回期望返回字符串”。任何想法如何解决这个问题

   func getLenderData(selectedLenderKey: String) -> String
    {

        let url = ""
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

        let task = session.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print("Error")
            }
            else{

                do{
                    //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                    //print(fecthdata)

                    let swiftyJSON = try JSON(data:data!)
                    let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                    let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                    let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                    let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                    let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                    let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue


                    print(lenderName)
                    print(oneYear)
                    print(twoYear)
                    print(threeYear)
                    print(fourYear)
                    print(fiveYear)


                }

                catch{
                    print("Error 2")
                }
            }

        }
        task.resume()
    }// end function

2 个答案:

答案 0 :(得分:0)

您可以创建模型并返回该模型:

struct Rates {
    let lenderName: String?
    let oneYear: String?
    let twoYear: String?
    let threeYear: String?
    let fourYear: String?
    let fiveYear: String?

    required init() {
        lenderName = nil
        oneYear = nil
        twoYear = nil
        threeYear = nil
        fourYear = nil
        fiveYear = nil
    }

    init(lenderName: String?, oneYear: String?, twoYear: String?, threeYear: String?, fourYear: String?, fiveYear: String?) {
        self.lenderName = lenderName
        self.oneYear = oneYear
        self.twoYear = twoYear
        self.threeYear = threeYear
        self.fourYear = fourYear
        self.fiveYear = fiveYear
    }
}

然后返回您创建的模型:

func getLenderData(selectedLenderKey: String, onCompletion: @escaping (Rates?) -> Void, onError: @escaping (NSError) -> Void) {
    let url = ""
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print("Error")
        }
        else{

            do{
                //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                //print(fecthdata)

                let swiftyJSON = try JSON(data:data!)
                let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue



                print(lenderName)
                print(oneYear)
                print(twoYear)
                print(threeYear)
                print(fourYear)
                print(fiveYear)

                let rate = Rates(lenderName: lenderName, oneYear: oneYear, twoYear: twoYear, threeYear: threeYear, fourYear: fourYear, fiveYear: fiveYear)
                onCompletion(rate)


            }

            catch{
                print("Error 2")
                onError(NSError(domain: "Some error description...", code: 0, userInfo: nil))
            }
        }

    }
    task.resume()
}// end function

现在您可以根据需要使用return value。要使用它,请使用以下代码:

getLenderData(selectedLenderKey: "someVal", onCompletion: { (rate) in
   // you can use the rate here
   let oneYear = rate.oneYear
}, onError: { (error) in
    // Error
})

答案 1 :(得分:0)

您可能希望将Promise用于此类实施。看看PromiseKit。你的代码会变成这样的

func getLenderData(selectedLenderKey: String) -> Promise<String> {
    return Promise { fulfill, reject in
        let url = ""
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print("Error")
            reject({ERROR})
        }
        else{

            do{
                //let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                //print(fecthdata)

                let swiftyJSON = try JSON(data:data!)
                let lenderName = swiftyJSON["lenders"][selectedLenderKey]["financial_institution"].stringValue
                let oneYear = swiftyJSON["lenders"][selectedLenderKey]["one_year"].stringValue
                let twoYear = swiftyJSON["lenders"][selectedLenderKey]["two_year"].stringValue
                let threeYear = swiftyJSON["lenders"][selectedLenderKey]["three_year"].stringValue
                let fourYear = swiftyJSON["lenders"][selectedLenderKey]["four_year"].stringValue
                let fiveYear = swiftyJSON["lenders"][selectedLenderKey]["five_year"].stringValue


                print(lenderName)
                print(oneYear)
                print(twoYear)
                print(threeYear)
                print(fourYear)
                print(fiveYear)

                fulfill({STRING})

            }

            catch{
                print("Error 2")
                reject({ERROR})
            }
        }

    }
    task.resume()
    }
}