首页 > 解决方案 > 我只想添加 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]
}

标签: iosswiftdictionary

解决方案


Dictionary.Values是字典值的特殊轻量级视图,以避免分配额外的内存。

为了能够连接多个值,您必须创建常规数组

var result = Array(cellAttrDict.values) + Array(supplHeaderAttrDict.values)
result += Array(supplFooterAttrDict.values)
result += Array(decorAttrDict.values)
return result as? [UICollectionViewLayoutAttributes]

推荐阅读