【问题标题】:Cannot assign a value of type T to type T无法将类型 T 的值分配给类型 T
【发布时间】:2019-10-19 01:06:34
【问题描述】:

我正在尝试创建一个接受泛型类型的可重用 ViewController。但我得到这个错误:

无法将“LevelType”类型的值分配给“LevelType”类型?

import Foundation
import UIKit

protocol SomeProtocol {
    var id: Int { get }
}

protocol VCProtocol: class {
    func showLevelScreen<LevelType>(level: LevelType)
}


class SomeVC<LevelType: SomeProtocol>: UIViewController, VCProtocol {

    typealias LevelType = LevelType

    var selectedLevel: LevelType? //Cannot assign value of type 'LevelType' to type 'LevelType?'

    func showLevelScreen<LevelType>(level: LevelType) {
        selectedLevel = level
    }


}

知道如何解决这个问题吗?

【问题讨论】:

  • typealias LevelType = LevelType的作用是什么?
  • 现在它是 LevelType = T 就像我的回答一样,没有 typealias 我无法编译,你知道该怎么做吗?
  • 我在没有 typealias 的情况下更新了我的答案,感谢 Cristik

标签: swift generics


【解决方案1】:

使用这个时编译器没有抱怨:

class SomeVC<T: SomeProtocol>: UIViewController, VCProtocol {

    var selectedLevel: T?

    func showLevelScreen<LevelType: SomeProtocol>(level: LevelType) {
        selectedLevel = level as? T
    }


}

【讨论】:

  • 你的答案在你测试时编译了吗?当我在 XCode 中尝试时,您提供的两个选项都没有编译
猜你喜欢
  • 1970-01-01
  • 2016-07-31
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 2019-01-31
  • 2019-11-17
  • 2022-11-11
  • 2022-11-11
相关资源
最近更新 更多