【问题标题】:Cannot convert value of type 'Int' to expected argument type '_?'无法将“Int”类型的值转换为预期的参数类型“_?”
【发布时间】:2016-08-01 20:16:06
【问题描述】:

注意:我是 Swift 的菜鸟

我正在使用Former

我正在从领域模型中获取数据。

let industries = realm.objects(Industry)

然后我尝试从中定义InlinePickerItem 的列表:

$0.pickerItems = industries.map({ industry in
    return InlinePickerItem(title: industry.name, value: industry.id)
})

但是 XCode 一直说:Cannot convert value of type 'Int' to expected argument type '_?',指向industry.id

我错过了什么吗?我不知道这个问题是来自Former 还是来自我在Swift 中不理解的东西。比如_?是什么类型?

更新

@dfri 发表评论后,尝试失败。从我对 Swift 的小理解来看,我知道 Swift 迷路了。所以我从闭包中提取了InlinePickerItem列表的初始化。

    let industries = realm.objects(Industry)
    let inlinePickerItems = industries.map({ industry in
        return InlinePickerItem(title: industry.name, displayTitle: nil, value: industry.id)
    })
    let catRow = InlinePickerRowFormer<ProfileLabelCell, String>(instantiateType: .Nib(nibName: "ProfileLabelCell")) {
        $0.titleLabel.text = "CATEGORY".localized
    }.configure {
        $0.pickerItems = inlinePickerItems
    }

调用InlinePickerItem(title: industry.name, displayTitle: nil, value: industry.id) 时错误消失了,但将它分配给$0.pickerItems 时我得到了一些新的东西,现在是:

Cannot assign value of type '[InlinePickerItem<Int>]' to type '[InlinePickerItem<String>]'

希望这将为您提供一些有用的提示。

【问题讨论】:

  • 如果你选择点击industries,它是什么类型的?
  • @vacawama 它的类型为Industry。 @dfri 谢谢,我会试试这个。
  • @dfri 我已经尝试过您提出的修改,但错误仍然存​​在。从您提出的建议开始,我已经用一些新的提示更新了帖子。也许你会有新的见解。
  • @dfri 谢谢!我只是将catRow 的类型更改为InlinePickerRowFormer&lt;ProfileLabelCell, Int&gt;,它运行顺利。你想写答案吗? ;)

标签: swift


【解决方案1】:

将数组分配给不同类型数组时类型不匹配

在重构代码之后(在“更新” 之后),现在很明显错误的来源是什么。

不可变的catRowInlinePickerRowFormer&lt;ProfileLabelCell, String&gt; 类型。从 [InlinePickerRowFormer] 的源代码中,我们看到类及其属性pickerItems 声明如下

public class InlinePickerRowFormer<T: UITableViewCell, S where T: InlinePickerFormableRow>
: ... {

    // ...

    public var pickerItems: [InlinePickerItem<S>] = []

    // ...
}

这里的关键是,对于一个实例InlinePickerRowFormer&lt;T,S&gt;,它的属性pickerItems 将是一个包含InlinePickerItem&lt;S&gt; 类型元素的数组。在您上面的示例中,SString

let catRow = InlinePickerRowFormer<ProfileLabelCell, String>
                                               /*       |
                                                        S = String */

因此pickerItemsInlinePickerItem&lt;String&gt; 实例的数组。

但是,您尝试将不可变的inlinePickerItems 附加到pickerItems,这意味着您尝试将InlinePickerItem&lt;Int&gt; 实例的数组分配给具有InlinePickerItem&lt;String&gt; 类型元素的数组;自然导致类型不匹配。

您可以通过以下方式解决这种类型不匹配:

  • 将您的 catRow 不可变设置为 InlinePickerRowFormer&lt;ProfileLabelCell, Int&gt; 类型。

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2017-01-09
    • 2017-02-08
    • 2018-10-01
    • 2021-12-31
    • 2016-06-04
    相关资源
    最近更新 更多