Swift Optionals Obnoxiousness

时间:2018-04-19 03:23:05

标签: arrays swift optional

为什么以下代码因value of optional type 'Section?' not unwrapped; did you mean to use '!' or '?'?编译错误而失败?

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).parentIDparentID已标记为可选。如果我将其与nil进行比较,为什么会出错?

1 个答案:

答案 0 :(得分:0)

使用以下代码: -

 let retrievedSections = [Section]()
 let rootSections = retrievedSections.filter() {
     return $0.parentID == nil && $0.name == config.rootSectionName
 }