【问题标题】:Expression type `String` is ambiguous without more context?表达式类型“字符串”在没有更多上下文的情况下是模棱两可的?
【发布时间】:2020-11-29 20:56:23
【问题描述】:

适用于 iPad 的 Swift Playgrounds 应用程序中的以下代码给了我一条错误消息:

Expression type `String` is ambiguous without more context

有人知道为什么会这样吗? 提前致谢。

import SwiftUI
import Foundation
import PlaygroundSupport

struct ContentView: View {
    @State private var progress: Double = 0.6
    var body: some View {
        VStack {
            Text("test")
            HStack {
                Slider(value: $progress)
                Text(String(format: "%.2f", progress))
            }
        }.border(Color.blue)
    }
}

PlaygroundPage.current.setLiveView(ContentView())

【问题讨论】:

    标签: swift string swift-playground


    【解决方案1】:

    是的,这很奇怪。出于某种原因,iPad 上的 Swift Playgrounds 有所不同。

    使用带说明符的字符串插值:

    替换

    Text(String(format: "%.2f", progress))
    

    Text("\(progress, specifier: "%.2f")")
    

    注意:

    如果您不希望文本跳来跳去,请使用具有等间距数字的字体,例如 Helvetica Neue。在Text 语句的末尾添加.font(Font.custom("Helvetica Neue", size: 20))

    【讨论】:

    • 感谢您的回答。你有更多关于“带说明符的字符串插值”的信息吗?
    【解决方案2】:

    您的代码没有问题...重新启动 Xcode

    【讨论】:

    • 这很奇怪,但我没有使用 Xcode,它是我使用的 Swift Playgrounds(版本 3.3.1)的 iPad 应用程序。你试过 iPad 应用吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多