【问题标题】:Cannot assign a value of type "String" to type "UILabel" in swift无法将“String”类型的值快速分配给“UILabel”类型
【发布时间】:2015-07-01 05:31:23
【问题描述】:

我正在制作一个关于数学测试​​随机生成器的程序。 但是当我创建一个随机操作时。我使用 arc4random_uniform() 创建一个随机数。这是函数。

func generateQuestion() {
        var randomoperation:UInt32 = arc4random_uniform(3)
        if randomoperation == 0 {
            operation = "+"
        }
        if randomoperation == 1 {
            operation = "-"
        }
        if randomoperation == 2 {
            operation = "X"
        }
        if randomoperation == 3 {
            operation = "/"
        }
    }

这会产生错误“无法将值类型“字符串”分配给在 swift 中键入“UILabel”” 你如何解决这个问题?

【问题讨论】:

  • 如果操作是您的 UILabel,则将文本写入 operation.text

标签: ios string swift uilabel uint32


【解决方案1】:
func generateQuestion() {
    switch arc4random_uniform(4) {
    case 0:
        operation.text = "+"
    case 1:
        operation.text = "-"
    case 2:
        operation.text = "X"
    case 3:
        operation.text = "/"
    default:
        operation.text = ""
    }
}

【讨论】:

    【解决方案2】:

    我认为operation 是您的标签名称,因此您可以通过这种方式为其分配文本:

    func generateQuestion() {
        var randomoperation:UInt32 = arc4random_uniform(3)
        if randomoperation == 0 {
            operation.text = "+"
        }
        if randomoperation == 1 {
            operation.text = "-"
        }
        if randomoperation == 2 {
            operation.text = "X"
        }
        if randomoperation == 3 {
            operation.text = "/"
        }
    }
    

    阅读此Apple Documentation 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      相关资源
      最近更新 更多