Swift 5 -通过泛型分配相同类型的属性值时出错


class SQS_Record {
var table: SQS_Table? = nil
}
class SQS_Table<RecordType: SQS_Record> {
func newRecord() -> RecordType {
      let new = RecordType()
         new.table = self               <<< ERROR: 
         return new
}
}

编译错误:无法将类型'SQS_Table'的值赋给类型'SQS_Table'

将来我希望:

class Project: SQS_Record {
var name: String = ""
}
let projectsTbl = SQS_Table<Project>(...)

并创建如下对象

let item = projectsTbl.newRecord()

根据您所描述的,您正在寻找协议,而不是类。例如:

// TableRecords know their table (and know other things)
// Note that TableRecord is a PAT (protocol with an associated type).
// There can not be any variables of type "TableRecord." It can only
// be used to constrain other types (as in Table below).
protocol TableRecord {
init(table: Table<Self>)
var table: Table<Self> { get }
}
// Project is a concrete TableRecord that also has a name.
// There can be variables of type Project.
struct Project: TableRecord {
let table: Table<Self>
var name: String = ""
init(table: Table<Self>) {
self.table = table
}
}
// Tables can create new records of the Record type
class Table<Record: TableRecord> {
func newRecord() -> Record {
let new = Record(table: self)
return new
}
}
let projects = Table<Project>()
let item = projects.newRecord() // item is of type Project

不可能在两个具有继承的类之间的递归引用中使用泛型类型我们为什么要这样做:

  1. var table: AnyObject?-字段可以存储任何类(ref)
  2. (表!SQS_Table)。reloadRecord(记录:self为!)Self) -基于Self的外来类型强制转换。

我无法用Protocol解决这个问题。从引用类型(Class - NOT struct)和类型强制转换继承——禁止

class SQS_Record {
var table: AnyObject? = nil
// Example - access to referenced table method and pass self param
func reload() {
guard __table != nil else { return }
(table as! SQS_Table<Self>).reloadRecord(record: self as! Self)
}
}
class SQS_Table<RecordType: SQS_Record> {
// RecordType - subclass of SQS_Record
func newRecord() -> RecordType {
let new = RecordType()
new.table = self               
return new
}
func reloadRecord(record: RecordType) {
...
}
}
class Project: SQS_Record {
...
}
let projectsTable = SQS_Table<Project>(...)
let newProjectRecord = projectsTable.newRecord()
newProjectRecord.reload()

最新更新