【问题标题】:Cannot assign value of type '(Array<_>).Type' to [CustomClass]无法将类型 '(Array<_>).Type' 的值分配给 [CustomClass]
【发布时间】:2018-07-30 19:11:55
【问题描述】:

我正在开发一个同时使用 Objective-C(旧代码)和 Swift(新代码以及将来添加的任何代码)的项目

我在 CoreData 模型中创建了两个新实体,我们称它们为文件夹和文件。文件夹与文件是一对多的关系。

这是我迄今为止提到的自动生成的子类的代码:

@interface Folder (CoreDataProperties)

+ (NSFetchRequest<Folder *> *)fetchRequest;
....
@property (nullable, nonatomic, retain) NSSet<File *> *files;
....
@end

@interface File (CoreDataProperties)

+ (NSFetchRequest<File *> *)fetchRequest;
....
@property (nullable, nonatomic, retain) Folder *folder;
....
@end

我正在处理我的 Swift 文件中的文件夹记录,我只是想设置我在另一个页面上具有 Folder.files 关系的属性。

这是我尝试设置的另一个 (Swift) 页面上的属性:

class FilesTableViewCell: UITableViewCell {

  ...
  var filesArray: [File]? = []
...
}

所以我正在尝试将特定文件夹记录的文件设置为该属性:

//some other Swift file
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  ...
  let cell = tableView.dequeueReusableCell(withIdentifier: FilesTableViewCellIdentifier) as! FilesTableViewCell
  let currentFolder = folderArray.last
  cell.filesArray = currentFolder?.files 
  // the line does not work I get a "Cannot assign value of type 'Set<File>?' to type '[File]?'" error
  return cell
....

即使我在“currentFolder?.files”前面添加“(Array)”,我仍然会收到以下错误:

"Cannot assign value of type '(Array<_>).Type' to type '[File]?'"

我在 Swift 方面没有经验,所以任何人都可以帮助我理解为什么这不起作用以及潜在的解决方案吗? (此时我将不得不对所有文件夹的文件进行核心数据提取,但如果我不必这样做,我宁愿不要那么低效)

【问题讨论】:

标签: objective-c arrays swift core-data


【解决方案1】:

请注意,files 不是Array,而是Set。 Set 与数组的不同之处在于它没有排序,因此当您遍历 Set 时,每次的顺序都可能(将)不同。但是Set 确保一个对象只能添加一次,因此如果您添加两个与Set 相同的对象,它将只包含一个对象 - 因此不会重复。

要从Set 获取Array,只需执行Array(yourSet),如果yourSet 的类型为Set&lt;File&gt;,则数组的类型为[File]

您只需将代码更改为:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    ...
    let cell = tableView.dequeueReusableCell(withIdentifier: FilesTableViewCellIdentifier) as! FilesTableViewCell

    if let currentFolder = folderArray.last, let files = currentFolder.files {
        let filesArray = Array(files)
        cell.filesArray = filesArray
    }

    return cell
    ....
}

【讨论】:

  • 谢谢你,这个解决方案非常有效。仍然不完全确定为什么执行 if let 语句首先解决了将其转换为数组的问题,但我将解决我作为临时修复的低效核心数据获取问题
  • 它不会将其转换为数组!let filesArray = Array(files) 这是将files 类型为Set&lt;File&gt; 的数组转换为[File] 类型的原因
  • 我倾向于使用 if let 而不是可选项,因为它更易于阅读,并且您知道只有在某些值存在并且对于可选项而不是 nil 时,您才会做某事...
  • 不,我的意思是 if let 允许我稍后将其转换为数组。无论如何再次感谢您的帮助老板,非常感谢
  • 是的,要么是那种方式,要么是更不安全的方式,强制展开 Array(currentFolder!.files!)...不是你想做的事
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2019-06-13
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多