我知道这听起来很荒谬,但现在我很困惑。
基本上,我有两个变量,一个是[Data]
,另一个是Array<Data>?
我需要将两者结合起来。
我尝试做var1+var2
,这给我发了错误,说不能对这两个进行二进制操作。
所以我用谷歌搜索,可以使用append方法,现在出现了更多问题:
这是我得到的代码和错误:
var a1:[Data] //a return value from other function
var a2:Array<Data>? //a parameter that's passed in
a1.append(contentsOf:a2) //Cannot use mutating member on immutable value: function call returns immutable value
a1+a2 //Binary operator '+' cannot be applied to operands of type 'Array<Data>' and 'Array<Data>?'
两个数组都可以为空,如何连接这两个数组?
答案 0 :(得分:2)
其中一个数组是可选的。您必须以某种方式处理可能的nil
值。
使用nil-coalescing的简单解决方案:
let concatenated = var1 + (var2 ?? [])
或者稍微复杂一点:
var concatenated = var1
if let var2 = var2 {
concatenated.append(var2)
}
当然还有其他可能的解决方案。
答案 1 :(得分:1)
Sulthan的答案是快速的解决方案,但是如果您在代码中执行很多操作,则可以重载+
来自动为您处理:
extension Array {
static func + (lhs: [Element], rhs: [Element]?) -> [Element] {
return lhs + (rhs ?? [])
}
}
答案 2 :(得分:1)
您还可以扩展RangeReplaceable Collection并实现自定义的append方法以及加法和变异加法运算符,如下所示:
const int magicColumnIndex = 2; // or whichever column you want the auto-selecting to happen on
void FreezeTableWidget::currentColumnChanged(const QModelIndex & mi)
{
const int col = mi.column();
if (col == magicColumnIndex)
{
// Auto-select the entire column! (Gotta schedule it be done later
// since it doesn't work if I just call selectColumn() directly at this point)
QTimer::singleShot(100, this, SLOT(autoSelectMagicColumn()));
}
}
void FreezeTableWidget::autoSelectMagicColumn()
{
// Double-check that the focus is still on the magic column index, in case the user moves fast
if (selectionModel()->currentIndex().column() == magicColumnIndex) frozenTableView->selectColumn(magicColumnIndex);
}
extension RangeReplaceableCollection {
public mutating func append<S: Sequence>(contentsOf sequence: S?) where Element == S.Element {
guard let sequence = sequence else { return }
reserveCapacity(count + sequence.underestimatedCount)
append(contentsOf: sequence)
}
}
extension RangeReplaceableCollection {
public static func += <S: Sequence>(lhs: inout Self, rhs: S?) where Element == S.Element {
guard let rhs = rhs else { return }
lhs.reserveCapacity(lhs.count + rhs.underestimatedCount)
lhs.append(contentsOf: rhs)
}
}
游乐场测试
extension RangeReplaceableCollection {
public static func + <S: Sequence>(lhs: Self, rhs: S?) -> Self where Element == S.Element {
guard let rhs = rhs else { return lhs }
var result = Self()
result.reserveCapacity(lhs.count + rhs.underestimatedCount)
result.append(contentsOf: lhs)
result.append(contentsOf: rhs)
return result
}
}