无法将类型T的值分配给类型T

时间:2019-10-19 01:06:34

标签: swift generics

我试图创建一个接受通用类型的可重用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
    }


}

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

1 个答案:

答案 0 :(得分:0)

使用此选项时,编译器不会发出任何抱怨:

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

    var selectedLevel: T?

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


}