【问题标题】:why I have to unwrap value before I use为什么我必须在使用前解开价值
【发布时间】:2016-07-25 14:29:03
【问题描述】:

块定义如下

 // Declare block ( optional )
 typealias sorting =   (([Schedule], [String]) -> [Schedule])?
    var sortSchedule: sorting   =   { (schedules, sortDescription) in
        var array =   [Schedule]()
        for string in sortDescription
        {
            for (index, schedule) in schedules.enumerate()
            {
                if string == schedule.startTime
                {
                    array.append(schedule)
                    break
                }
            }
        }
        return array
    }

在某些时候,我通过做来调用一个块

 let allSchedules =   sortSchedule?(result, sortDescription())
 for schedule in allSchedules // Xcode complains at here
 {
    ..........
 }

我正在使用?,因为我想确保如果该块存在,那么就做点什么。但是,Xcode 抱怨 for 循环

 value of optional type [Schedule]? not upwrapped, did you mean to use '!' or '?'?

我不知道为什么,因为一个块的返回类型是一个可以有 0 个或多个项目的数组。

有谁知道为什么 xcode 抱怨。

【问题讨论】:

  • 为什么我得到一个downvow伙计们?我想知道它的原因,这样我以后就可以避免问这样的问题了。

标签: ios swift optional forced-unwrapping


【解决方案1】:

您在let allSchedules = sortSchedule?(result, sortDescription()) 行中使用? 不是“确定是否存在该块”,而只是为了说明,您知道它可以是nil。幕后allSchedules 有类型Array<Schedule>?。并且您不能将for in 循环用于nil。你最好使用可选绑定:

if let allSchedules = sortSchedule?(result, sortDescription())
{
    for schedule in allSchedules
    {
       //..........
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多