I created a custom class called Weather and declared an array of Weather objects.
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()
}
}
I pass the array into a function and I append the values to the weatherArrays parameter. However, when I compile I get the error, "Cannot use mutating member on immutable value: 'weatherArrays' is a 'let' constant."
The Weather class was originally a struct but I got this same error and I read up and found that struct values cannot be edited in a function because it is pass by value. I changed the struct to a class and I am still getting this same error? Why is it saying "'weatherArrays' is a 'let' constant" when I declared weatherArrays as a var?