Search code examples
iosswiftoption-typeforced-unwrapping

why I have to unwrap value before I use


A block is defined like below

 // 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
    }

At some points, I am invoking a block by doing

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

Im using ? because I want to make sure that if the block exists, then do something. However, Xcode complains for the for loop

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

Im not sure why because the return type of a block is an array which can have 0 or more than one items.

Does anyone know why xcode is complaining.


Solution

  • You are use ? in line let allSchedules = sortSchedule?(result, sortDescription()) not "for sure that if the block exists", but just for note, that you understand that it can be nil. Behind scene allSchedules have type Array<Schedule>?. And you can not use for in cycle for nil. You better use optional binding:

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