[英]Cannot assign value of type 'Int' to type 'Int?.Type' Swift 5
I am trying to pass a value from one view controller to another of type Int
.我试图将一个值从一个视图 controller 传递给另一个
Int
类型的值。
Here is how I am invoking my sugue:这是我调用我的 sugue 的方式:
if questionNumber + 1 == quizBrain.quiz.count{
self.performSegue(withIdentifier: "goToScore", sender: self)
}
My prepare
function is:我
prepare
的 function 是:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToScore" {
let destinationVC = segue.destination as! ResultViewController
destinationVC.finalScore = quizBrain.getScore()
}
}
Here is my destination view class:这是我的目标视图 class:
import UIKit
class ResultViewController: UIViewController {
var finalScore = Int?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
quizBrain.getScore()
fetches a value of type Int
. quizBrain.getScore()
获取Int
类型的值。 I am trying to pass this value and catch it in the other view in var finalScore
.我试图传递这个值并在
var finalScore
的另一个视图中捕获它。
The error I am getting is:我得到的错误是:
Cannot assign value of type 'Int' to type 'Int?.Type'
I am not sure what this particularly means, I am new to Swift and was unable to find something similar with a type Int?.Type
.我不确定这特别意味着什么,我是 Swift 的新手,无法找到与
Int?.Type
类型类似的东西。 I am also running into a similar issue if I try passing a String
in a different project.如果我尝试在不同的项目中传递
String
,我也会遇到类似的问题。
Changing var finalScore = Int?
改变
var finalScore = Int?
to var finalScore:Int = 0
fixed it, Not sure if this is a Swift version issue. var finalScore:Int = 0
修复了它,不确定这是否是 Swift 版本问题。 would be helpful if somebody could confirm why this worked.如果有人可以确认为什么这样做会有所帮助。
An optional in Swift is a type that can hold either a value or no value. Swift 中的可选项是一种可以保存值或不保存值的类型。 Optionals are written by appending a?
选项是通过附加一个? to any type:
任何类型:
You should define an optional integer like:您应该定义一个可选的 integer ,例如:
var finalScore: Int? //now the value of finalScore can be nil or any integer value etc.
While using the option values, there are couple of ways:使用选项值时,有几种方法:
if finalScore != nil {
print(finalScore!)
}
or或者
guard let score = finalScore else {
return
}
print(score)
or或者
print(finalScore ?? 0)
For more info, you can refer Apple Doc: https://developer.apple.com/documentation/swift/optional有关更多信息,您可以参考 Apple 文档: https://developer.apple.com/documentation/swift/optional
Swift basics: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_399 Swift basics: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_399
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.