ios - 我只想添加 2 个字典的值
问题描述
我有一个 swift 代码,它会自动从目标 C 迁移到 swift 出现错误的地方
“二元运算符 '+' 不能应用于两个 'Dictionary.Values' 操作数”。
因为我试图添加不允许的字典的值。但是如何明智地添加其他值。下面是我收到此错误的代码。
var result = cellAttrDict.values + supplHeaderAttrDict.values
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var i: Int
var begin = 0
var end = unionRects.count
var cellAttrDict: [AnyHashable : Any] = [:]
var supplHeaderAttrDict: [AnyHashable : Any] = [:]
var supplFooterAttrDict: [AnyHashable : Any] = [:]
var decorAttrDict: [AnyHashable : Any] = [:]
for i in 0..<unionRects.count {
if rect.intersects(unionRects[i] as! CGRect) {
begin = i * unionSize
break
}
}
i = unionRects.count - 1
while i >= 0 {
if rect.intersects(unionRects[i] as! CGRect) {
end = min((i + 1) * unionSize, allItemAttributes.count)
break
}
i -= 1
}
for i in begin..<end {
let attr = allItemAttributes[i] as? UICollectionViewLayoutAttributes
if rect.intersects(attr?.frame ?? 0 as! CGRect) {
switch attr?.representedElementCategory {
case .supplementaryView?:
if (attr?.representedElementKind == CHTCollectionElementKindSectionHeader) {
if let indexPath = attr?.indexPath, let attr = attr {
supplHeaderAttrDict[indexPath] = attr
}
} else if (attr?.representedElementKind == CHTCollectionElementKindSectionFooter) {
if let indexPath = attr?.indexPath, let attr = attr {
supplFooterAttrDict[indexPath] = attr
}
}
case .decorationView?:
if let indexPath = attr?.indexPath, let attr = attr {
decorAttrDict[indexPath] = attr
}
case .cell?:
if let indexPath = attr?.indexPath, let attr = attr {
cellAttrDict[indexPath] = attr
}
@unknown default:
break
}
}
}
var result = cellAttrDict.values + supplHeaderAttrDict.values
result = result + supplFooterAttrDict.values
result = result + decorAttrDict.values
return result as? [UICollectionViewLayoutAttributes]
}
解决方案
Dictionary.Values
是字典值的特殊轻量级视图,以避免分配额外的内存。
为了能够连接多个值,您必须创建常规数组
var result = Array(cellAttrDict.values) + Array(supplHeaderAttrDict.values)
result += Array(supplFooterAttrDict.values)
result += Array(decorAttrDict.values)
return result as? [UICollectionViewLayoutAttributes]
推荐阅读
- python - 将 Pandas 数据框转换为无向边缘列表
- reactjs - 添加身份验证状态时,屏幕卡在启动画面
- javascript - 如何保持状态不断出现在 JavaScript 函数到 HTML
- mysql - 我在尝试创建表时不断收到 mysql 中的 1064 错误
- reactjs - 如何在 React 中使用 react-date-range 发布请求日期?
- c# - Xamarin GUI 更新未发生异步
- powershell - *已解决* PowerShell 脚本来实现 ipsec 规则
- postgresql - PostgreSQL 中时间格式的常见做法
- perl - html2text 命令行 打破 html
- r - 如何根据条件删除一列的值,增加其他列的数量