【问题标题】:How to print multiple objects in a single print statement in Swift?如何在 Swift 的单个打印语句中打印多个对象?
【发布时间】:2020-05-04 07:35:28
【问题描述】:

我正在构建一个从 OpenWeatherMap API 获取 JSON 数据的应用。 在我的应用中,我有这样的结构:

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
}

在我的一个打印语句中,我想在一个打印语句中打印出 Coords 中的所有值,例如 print(decodedData.coord.lat)

我应该如何格式化打印语句,以便它可以同时打印lat 值和lon 值?

【问题讨论】:

  • 你的意思是print(decodedData.coord.lat, decodedData.coord.lon)
  • 是的!谢谢你:)

标签: swift xcode syntax swift-playground


【解决方案1】:

print 接受 Any... 作为其第一个参数。文档中的第一句话说:

您可以将零个或多个项目传递给print(_:separator:terminator:) 函数。

这意味着您可以在该位置传入任意数量的参数,它们都会被打印出来:

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

默认情况下,这两个东西会用空格隔开。你可以传入一个separator: 参数来指定你想要的分隔符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多