Search code examples
iosswiftnsarray

Formatting NSArray for Swift


I have trouble formatting the NSArray

let temp = json.value(forKeyPath: "data.current_condition.temp_F") as Any
                                                  
                            DispatchQueue.main.async {
                                self.setWeather(temp: temp as! NSArray  )
                              }
func setWeather(  temp: NSArray) {
          TempLabel.text = "\(temp)"

When I run the program TempLabel only shows " ( " because it's in NSArray form. I am not sure how do I get rid of "(".


Solution

  • Using the description of the object to show it on the UI is quite fragile, and could change anytime internally in iOS.

    What I would try instead is to cast the result of your json value into Swift types. In your case [Int] should work. Then use one of the collection methods to convert the Int array to String.

    Try something like this:

    let temp = json.value(forKeyPath: "data.current_condition.temp_F") as! [Int]
    TempLabel.text = temp.map({ "\($0)" }).joined(separator: ", ")