在调用self.init之前自己使用的iOS Swift便利初始化程序

时间:2017-09-05 20:13:45

标签: ios swift

所以我一直在努力创造一个"时期" class,具有以下属性:

class PTPeriod {

    // MARK: Stored Properties

    var start: Date
    var end: Date
    var place: PTPlace?


//MARK: DESIGNATED NITIALIZER
init(start: Date, end: Date, place: PTPlace? = nil) {
    self.start = start
    self.end = end
    self.place = place

}

我想用一个接受如下字典的方便初始化它:

        {
           "close" : {
              "day" : 1,
              "time" : "0000"
           },
           "open" : {
              "day" : 0,
              "time" : "0900"
           }
        }

这是我的初始化程序,最初我将繁重的工作放入辅助方法中。但是,我得到了同样的错误,所以我删除了辅助方法,但错误仍在发生。不确定它认为我在呼唤自己。

更新:将日期格式移动到日期格式化程序扩展名中,但错误仍然存​​在!不确定为什么。新的init显示:

我的新方便初学者:

// MARK: Convenience init for initializing periods pulled from Google Place API
convenience init?(placeData: [String:Any], place: PTPlace? = nil) throws {
    var start: Date? = nil
    var end: Date? = nil
    var formatter = DateFormatter()

    do {
        for (key, value) in placeData {
            let period = value as! [String: Any]
            if (key == "open") {
                start = try formatter.upcoming_date(with: period)
            } else if (key == "close") {
                end = try formatter.upcoming_date(with: period)
            } else {
                break
            }
        }
        if (start != nil && end != nil) { self.init(start: start!, end: end!, place: place) }
        else { print("we f'd up") }

    }

    catch { print(error.localizedDescription) }
}

这是我的DateFormatter.upcoming_date方法:

   func upcoming_date(with googlePlacePeriod: [String: Any]) throws -> Date? {
    if let day = googlePlacePeriod["day"] as? Int {
        if (day < 0) || (day > 6) { throw SerializationError.invalid("day", day) } // throw an error if day is not between 0-6
        if let time = googlePlacePeriod["time"] as? String {
            if time.characters.count != 4 { throw SerializationError.invalid("time", time) } // throw an error if time is not 4 char long
            var upcoming_date: Date
            let gregorian = Calendar(identifier: .gregorian)

            let current_day_of_week = Date().getDayOfWeekInt()
            let dayOfPeriod = day + 1

            ///TRUST THAT THIS WORKS... NO JODAS
            var distance = dayOfPeriod - current_day_of_week // inverse = false

            if (dayOfPeriod < current_day_of_week) {
                switch distance {
                case -1: distance = 6
                case -2: distance = 5
                case -3: distance = 4
                case -4: distance = 3
                case -5: distance = 2
                case -6: distance = 1
                default: break
                }
            }
            /** time example: "1535" translates into 3:35PM
             first two characters in string are "hour" (15)
             last two characters in string are "minute(35)
             **/

            let hour = Int(time.substring(to: time.index(time.startIndex, offsetBy: 2)))!
            let minute = Int(time.substring(from: time.index(time.endIndex, offsetBy: -2)))


            upcoming_date = Date().fastForward(amount: distance, unit: "days", inverse: false)!
            var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: upcoming_date)
            components.hour = hour
            components.minute = minute
            upcoming_date = gregorian.date(from: components)!
            return upcoming_date
        }
        else { throw SerializationError.missing("time") }
    }
    else { throw SerializationError.missing("day") }
}

1 个答案:

答案 0 :(得分:1)

你有一个可用的初始化程序,所以如果它失败了,你必须{ id: 'f212d399-f139-4d76-b892-7c2a83281f9b' }让它知道它失败了:

return nil

另外,在if (start != nil && end != nil) { self.init(start: start!, end: end!, place: place) } } else { print("we f'd up") return nil } - do中,您需要

  • 重新catch throw块中的错误

    catch
  • 完全消除catch { print(error.localizedDescription) throw error } - do个区块;或

  • 只是catch

    return nil

    如果你这样做,你可能不会将这个可用的初始化程序定义为catch { print(error.localizedDescription) return nil } ,因为你不再抛出它。

鉴于您不太可能对抛出的错误做任何有意义的事情,我只是让它成为一个不会抛出的可用的初始化器:

throws