Swift,MyClass,可选(MyClass?)无法转换为MyClass

时间:2019-06-04 15:24:42

标签: ios swift generics

我正在尝试使用泛型为NSManagedObject的子类提供通用方法,但是当Swift似乎无法找到/将泛型转换为具体类时,我遇到了错误:

from kivy.uix.textinput import TextInput
...
class SecondScreen(Screen):

    def clear_inputs(self):
        main = self.manager.get_screen('Main')
        for child in reversed(main.ids.container.children):
            if isinstance(child, TextInput):
                child.text = ''
/// NSManagedObject+Helper.swift
///
import Foundation

extension NSManagedObject {
    public static func inserta<T>() -> T? {
        let name = self.entityName()
        return CoreDataManager.createRow(inEntityNamed: name) as? T
    }
}
/// MySwitch+CoreDataClass.swift
///
import Foundation
import CoreData

@objc(MySwitch)
public class MySwitch: NSManagedObject {

}

因此,第8行中的调用给出了错误'MySwitch?'不能转换为“ MySwitch”
通过删除转换,我得到了错误:无法推断出通用参数'T'
通过将第8行更改为 1 extension MySwitch { 2 3 @NSManaged public var key: String? 4 @NSManaged public var sValue: String? 5 @NSManaged public var value: String? 6 7 public class func insert(withKey key: String, value: String, sValue: String? = nil) throws -> MySwitch { 8 if let row = self.inserta() as? MySwitch { 9 row.key = key 10 row.value = value 11 if let sValue = sValue { 12 row.sValue = sValue 13 } 14 return row 15 } 16 throw CoreDataError.create_row 17 } 18 } ,它将显示相同的'MySwitch?'不能转换为“ MySwitch” 错误。

我想我没有告诉Swift MySwitch.self.inserta() as? MySwitch的含义,因为我也收到警告:

T

1 个答案:

答案 0 :(得分:0)

找到了我与泛型有关的问题。我首先需要将MySwitch的变量声明为可选变量:

1 let mySwitch: MySwitch? = inserta()
2 if let row = mySwitch {...

这样,我就告诉Swift T是什么类型。