Search code examples
swiftxcodesyntaxswift-playground

How to print multiple objects in a single print statement in Swift?


I'm building an app that fetches JSON-data from the OpenWeatherMap API. In my app I have structs like these:

struct WeatherData: Decodable {
    let name: String
    let main: Main
    let coord: Coord
}

struct Main: Decodable {
    let temp: Double
}

struct Coord: Decodable {
    let lon: Double
    let lat: Double
}

In one of my print statements, I want to print out all the values from Coords in the one print statement, like this print(decodedData.coord.lat)

How should I format the print statement so it can print both the lat value and the lon value?


Solution

  • The print accepts a Any... as its first parameter. The first sentence in the documentation says:

    You can pass zero or more items to the print(_:separator:terminator:) function.

    That means you can pass in any number of arguments in that position, and they will all get printed out:

    print(decodedData.coord.lat, decodedData.coord.lon)
    

    The two things will be separated by a space by default. You can pass in a separator: argument to specify what separator you want.