无法将'Int'类型的值转换为预期的参数类型'_?'

时间:2016-04-11 15:10:42

标签: swift

注意:我是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>]' 时我得到了新内容:

var task = UserManager.FindByIdAsync(User.Identity.GetUserId()); // Uses the same DB Context
DbContext.Stages.Add(...);
await task;

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

1 个答案:

答案 0 :(得分:1)

将数组分配给不同类型的数组

时类型不匹配

在重新分解代码之后(“update”之后),它现在显而易见的是错误的来源。

不可变catRow的类型为InlinePickerRowFormer<ProfileLabelCell, String>。从[InlinePickerRowFormer]的源代码我们看到该类及其属性pickerItems声明如下

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

    // ...

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

    // ...
}

这里的关键是,对于实例InlinePickerRowFormer<T,S>,其属性pickerItems将是一个类型为InlinePickerItem<S>的数组。在上面的示例中,SString

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

因此pickerItemsInlinePickerItem<String>个实例的数组。

但是,您尝试将不可变inlinePickerItems附加到pickerItems,这意味着您尝试将InlinePickerItem<Int>个实例的数组分配给类型为{{InlinePickerItem<String>的数组。 1}};自然导致类型不匹配。

您可以通过以下方式解决此类型不匹配问题:

  • catRow不可变设置为InlinePickerRowFormer<ProfileLabelCell, Int>类型。
相关问题