gpt4 book ai didi

swift - 通过函数传递时不能修改对象数组?

转载 作者:行者123 更新时间:2023-11-28 11:28:44 25 4
gpt4 key购买 nike

我创建了一个名为 Weather 的自定义类并声明了一个 Weather 对象数组。

import Foundation

class Weather {
var cityName:String
var temperature:Double
var temperatureMax:Double
var temperatureMin:Double

init(cityName: String, temperature: Double, temperatureMax: Double, temperatureMin: Double) {

self.cityName = cityName
self.temperature = temperature
self.temperatureMax = temperatureMax
self.temperatureMin = temperatureMin

}
}

import UIKit
import SwiftyJSON

class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var weatherArrays = [Weather]()
findLocation(zipCode: "11210", weatherArrays: weatherArrays)
print(weatherArrays[0].cityName)
}

func findLocation(zipCode: String, weatherArrays: [Weather])
{
let zip = zipCode
let appID = "245360e32e91a426865d3ab8daab5bf3"
let urlString = "http://api.openweathermap.org/data/2.5/weather?zip=\(zip)&appid=\(appID)&units=imperial"
let request = URLRequest(url: URL(string: urlString)!)
URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
do
{
let json = try JSONSerialization.jsonObject(with: data!) as! NSDictionary
let main = json["main"] as! [String:Any]
let temp = main["temp"]! as! Double
let name = json["name"]! as! String
let tempMax = main["temp_max"]! as! Double
let tempMin = main["temp_min"]! as! Double
weatherArrays.append(Weather(cityName: name, temperature: temp, temperatureMax: tempMax, temperatureMin: tempMin))
}
catch
{
print("Error")
}

}.resume()
}

}

我将数组传递给函数,并将值附加到 weatherArrays 参数。但是,当我编译时出现错误,“不能在不可变值上使用可变成员:'weatherArrays' 是一个'let'常量。”

Weather 类最初是一个结构体,但我遇到了同样的错误,我仔细阅读后发现无法在函数中编辑结构体值,因为它是按值传递的。我将结构更改为一个类,但仍然出现同样的错误?当我将 weatherArrays 声明为 var 时,为什么它说“'weatherArrays' 是一个'let'常量”?

最佳答案

这里有一个更好的代码方法

import UIKit
import SwiftyJSON

struct Weather {
let cityName:String
let temperature:Double
let temperatureMax:Double
let temperatureMin:Double
}
class ViewController: UIViewController {

@IBOutlet weak var myLabel: UILabel!

var array = [Weather]()
let appID = "245360e32e91a426865d3ab8daab5bf3"

override func viewDidLoad() {
super.viewDidLoad()

findLocation(zipCode: "11210"){ array in
guard let array = array else {
print("Error")
return
}
print(array.first?.cityName ?? "no city name found")
}

}

func buildUrl(queryItems: [URLQueryItem]) -> URL?{
var components = URLComponents()
components.scheme = "http"
components.host = "api.openweathermap.org"
components.path = "/data/2.5/weather"
components.queryItems = queryItems
return components.url
}

func findLocation(zipCode: String, completionHandler: @escaping (_ array: [Weather]?) -> ()){

guard let url = buildUrl(queryItems: [URLQueryItem(name: "zip", value: zipCode), URLQueryItem(name: "appID", value: appID), URLQueryItem(name: "units", value: "imperial")]) else {
print("Error in building url")
return
}

let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
guard let data = data else {
print(error?.localizedDescription ?? "")
completionHandler(nil)
return
}
do{
var array = [Weather]()
let json = try JSON(data: data)
if json["cod"].intValue == 200{
let main = json["main"]
let temp = main["temp"].doubleValue
let name = json["name"].stringValue
let tempMax = main["temp_max"].doubleValue
let tempMin = main["temp_min"].doubleValue
array.append(Weather(cityName: name, temperature: temp, temperatureMax: tempMax, temperatureMin: tempMin))
completionHandler(array)
}else{
completionHandler(nil)
}

} catch let error{
print(error)
}
}.resume()
}

}

对模型使用struct,我们不必写init方法

当您知道不会更改数据时,请使用 let 而不是 var

不要使用 NSDictionary。

您在调用函数后立即编写了 print 语句,因为数组只有在对服务器的调用完成后才会被填充。所以我使用了完成处理程序

我看到您已经安装了 SwiftyJSON,但实际上并没有使用它的好处。看解析部分。

关于您遇到的错误是因为 Swift 是按值传递的,即当您传递数组对象时,您实际上传递的是它的副本而不是实际数组。如果你想修改同一个数组,你需要我们inout。可以为 that 找到一个很棒的教程

编辑:按照@rmaddy 的建议,通过返回一个新数组使代码更安全。请参阅他的评论以获取更多信息。

关于swift - 通过函数传递时不能修改对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57387257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com