Arrays 斯威夫特的选择令人讨厌
为什么以下代码失败,且可选类型“Section”的Arrays 斯威夫特的选择令人讨厌,arrays,swift,optional,Arrays,Swift,Optional,为什么以下代码失败,且可选类型“Section”的值未展开;你想用“!”吗或“?”?编译错误 struct Section { let parentID:Int? let name:String } // sometime later ... var retrievedSections:[Section]? // Code to retrieve sections here. /* Filter out any sections that are not under au
值未展开;你想用“!”吗或“?”?
编译错误
struct Section
{
let parentID:Int?
let name:String
}
// sometime later ...
var retrievedSections:[Section]?
// Code to retrieve sections here.
/* Filter out any sections that are not under automation root section. */
if let retSections = retrievedSections
{
/* Find the root section in the retrieved sections. */
let rootSections = retSections.filter()
{
return ($0).parentID == nil && ($0).name == config.rootSectionName
}
if rootSections.count != 1
{
print("Invalid root section count!")
}
else
{
model.rootSection = rootSections[0]
model.sections = retSections.filter()
{
return ($0).isRoot() || ($0).parentID == model.rootSection.id
}
}
}
编译器抱怨($0).parentID
<代码>父ID已标记为可选。如果我将其与nil
进行比较,为什么会给出错误?使用以下代码:-
let retrievedSections = [Section]()
let rootSections = retrievedSections.filter() {
return $0.parentID == nil && $0.name == config.rootSectionName
}
retrievedSections
中元素的类型是什么?我猜是[部分?]
。这完全有道理。你的$0
需要拆开…@Honey[Section]AFAIK,这是唯一的原因。尝试重新启动mac/Xcode。如果它不起作用,请共享一个最小可复制代码config
的类型是什么?是部分
还是部分?
?选项是您的朋友。不,不是错误的原因。我用更完整、更简化的代码更新了上面的代码。retrievedSections是一个可选的数组,但在这两者之间,我将其评估为非可选的(retSections)。@Baddingtoncat如果它是一个可选的数组,那么它是[Section?]
,而不是[Section]
。如果在数组上运行if
,则无法解决此问题。@CharlesSrstka(正如您在数组上方看到的)一开始是可选的,但不是元素。在任何情况下,都找到了罪魁祸首:model.rootSection是可选的,因此它应该是return($0)。isRoot()| |($0)。parentID==model.rootSection?.id
@baddingtoncat好的,有意义。为了将来参考,下次请更清楚是哪一行导致了错误。您的描述使它看起来像是在return($0).parentID==nil&($0.name==config.rootSectionName
)上发生的错误(问题的原始版本中甚至没有另一行)。