【问题标题】:Cannot assign value of type 'Int' to type 'Int?.Type' Swift 5无法将“Int”类型的值分配给“Int?.Type”Swift 5
【发布时间】:2020-04-20 04:52:45
【问题描述】:

我正在尝试将一个值从一个视图控制器传递到另一个 Int 类型的控制器。

这是我调用 sugue 的方式:

if questionNumber + 1 == quizBrain.quiz.count{
            self.performSegue(withIdentifier: "goToScore", sender: self)
        }

我的prepare 函数是:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToScore" {
    let destinationVC = segue.destination as! ResultViewController
    destinationVC.finalScore = quizBrain.getScore()
        }
    }

这是我的目标视图类:

import UIKit

class ResultViewController: UIViewController {

    var finalScore =  Int?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

quizBrain.getScore() 获取Int 类型的值。我试图传递这个值并在var finalScore 的另一个视图中捕获它。

我得到的错误是:

Cannot assign value of type 'Int' to type 'Int?.Type'

我不确定这特别意味着什么,我是 Swift 新手,无法找到与 Int?.Type 类型类似的东西。如果我尝试在不同的项目中传递String,我也会遇到类似的问题。

【问题讨论】:

  • = 替换为:。您将声明类型而不是分配默认值。

标签: ios swift swift5


【解决方案1】:

var finalScore = Int? 更改为var finalScore:Int = 0 已修复!不确定这是否是 Swift 版本问题,如果有人能确认为什么会这样会很有帮助。

【讨论】:

    【解决方案2】:

    Swift 中的可选项是一种可以保存值或不保存值的类型。可选项是通过附加一个 ?任何类型:

    您应该定义一个可选整数,如:

    var finalScore: Int? //now the value of finalScore can be nil or any integer value etc.
    

    在使用选项值时,有几种方法:

    if finalScore != nil {
        print(finalScore!)
    }
    

    guard let score = finalScore else {
        return
    }
    
    print(score)
    

    print(finalScore ?? 0)
    

    更多信息,你可以参考苹果文档:https://developer.apple.com/documentation/swift/optional

    Swift 基础知识:https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_399

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多