无法将 'Int' 类型的值分配给 Swift 5 'Int?.Type'类型



我正在尝试将一个值从一个视图控制器传递到另一个类型为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,我也会遇到类似的问题。

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

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)

有关更多信息,您可以参考 Apple Doc: https://developer.apple.com/documentation/swift/optional

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

最新更新