ios - 函数式编程中非可选数组的可选对象
问题描述
我有一个 Type1 的可选 object1。我想将它转换为 Type2 的数组(非可选,如果 object1 为 nil,则为空)。
Type2 对象由 Type1 对象构成。
所以我试过这样:
func convert(object1: Type1?) -> [Type2] {
object1.map {
[
Type2($0)
]
}
}
但我得到这个错误:
Cannot convert return expression of type '[Type2]?' to return type '[Type2]'
注意:Type2 初始化程序不能将可选值作为参数。
如果有人有想法,请提前致谢
解决方案
尝试
func convert(object1: Type1?) -> [Type2] {
guard let res = object1 else { return [] }
return [Type2(res)]
}
推荐阅读
- jquery - 在 jquery datepicker 中仅启用 2 个日期,例如当前日期和昨天日期
- php - 创建客户属性在magento 2中不起作用
- android - 获取孩子的价值观
- python - 嵌套序列化现在不创建一个 forignkey 它需要一个新的对象而不是 'id'
- python - 如何在迭代时成功弹出/删除字典项
- css - ReactJS+MaterialUI v1 自动嵌套列表填充
- python - 我们如何在 python 中使用压缩进行日志旋转?
- excel - 我可以使用索引匹配对字符串中的多个文本进行通配符吗
- mongodb - 对数组 mongodb 的索引进行排序
- java - 在服务器上上传 5 个相机图像时,图像在 android 中变得模糊