簡體   English   中英

Swift 返回隨機字符串

[英]Swift return random String

為什么這僅適用於數字? 我可以顯示隨機數,但不能顯示隨機字符串。 我該如何格式化?

struct ContentView: View {

    let results = [8, 5, 10].map(Result.init)
    let orden = ["hej", "ta", "tojj"].map(Ord.init)

    @State var randomResult: Result?
    @State var randomOrd: Ord?

    var body: some View {
        VStack {
            Button(action: {


               self.randomResult = self.results.randomElement()
                self.randomOrd = self.orden.randomElement()
            }) {
                Text("Button title, \(randomResult?.score ?? 0)")

               Text(randomOrd?.ord ?? 0)
               // THIS DOESN'T WORK even when i put an Int around it 


            }

        }
    }
}

默認值0絕對不是字符串。 等效字符串是一個空字符串

Text(randomOrd?.ord ?? "")

文本初始值設定項采用StringProtocol類型的content

init<S>(_ content: S) where S : StringProtocol

請注意,在

Text("Button title, \(randomResult?.score ?? 0)")

您正在傳遞一個有效的字符串(帶有內插整數)。 然而,在

Text(randomOrd?.ord ?? 0)

似乎您試圖直接傳遞一個無效的int。

基於ord的類型:

如果是字符串,則應將其實現為:

Text(randomOrd?.ord ?? "0") // OR maybe Text(randomOrd?.ord ?? "")

如果它是一個整數:

Text("\(randomOrd?.ord ?? 0)")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM