【问题标题】:Convert Optional<Double> to String将 Optional<Double> 转换为字符串
【发布时间】:2018-07-13 21:04:25
【问题描述】:

这是我目前用来获取日历事件位置(在本例中为纬度)的代码。

let latitude = event.structuredLocation?.geoLocation?.coordinate.latitude
print(latitude) // Optional<Double>

print("\(String(describing: latitude))") // not working

因为纬度的类型是Optional&lt;Double&gt;,所以我想返回一个值为的字符串(如“49,9202221”)。

编辑:

if let latitude = event.structuredLocation?.geoLocation?.coordinate.latitude {
     print(latitude) // gets rounded - How to avoid this?
}

如何将此值转换为字符串不显示"Optional(...)"?

【问题讨论】:

    标签: swift integer double


    【解决方案1】:

    只需解开纬度如下:

    if let latitude = event.structuredLocation?.geoLocation?.coordinate.latitude {
         print(String(format: "%.16f", latitude)) // change 16 to the number of digits that you want after comma
    } else {
         print("latitude is nil")
    }
    

    【讨论】:

    • 但不是geoLocation。纬度值被四舍五入。我可以避免这种情况吗? @Anton Kondrashov
    • 你能显示输出吗?我不明白圆了多少。
    • Optional(23.829600769999997) --> 23.82960077
    猜你喜欢
    • 2015-02-07
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多