小编abj*_*ato的帖子

如何制定描述字符串表示的枚举的协议?

我有一个方法,它调用某个管理器的方法来用某个键保存 int 值。我的方法接收 int 和一些 EnumKey 枚举值作为键,挤出 EnumKey 的 rawValue 并将其作为字符串传递给管理器:

set(value: Int, forKey key: EnumKey) {
    SomeManager.saveIntValueWithStringKey(valueToSave: value, keyToSave: key.rawValue)
}

enum EnumKey: String { 
    case One="first key"
    case Two="second key"
}
Run Code Online (Sandbox Code Playgroud)

我想通过允许我的方法接收带有字符串原始值而不是 EnumKey 的每个枚举来使其更加通用。在方法的实现中,我将关键参数的类型从 EnumKey 替换为 GenericKey 协议,并使 EnumKey 符合此协议:

 set(value: Int, forKey key: GenericKey) {
    SomeManager.saveIntValueWithStringKey(valueToSave: value, keyToSave: key.rawValue)
}

protocol GenericKey {
    var rawValue: String { get }
}

enum EnumKey: String, GenericKey { 
    case One="first key"
    case Two="second key"
}
Run Code Online (Sandbox Code Playgroud)

但这String, GenericKey看起来有点难看。我希望每个可表示字符串的枚举都能自动适应,而不需要提及它除了 RawRepresentable …

generics enums swift swift-protocols rawrepresentable

4
推荐指数
1
解决办法
2499
查看次数

当 WKExtension.scheduleBackgroundRefresh 应该调用 scheduleCompletion 处理程序时?

我正在尝试使用这样的行安排后台任务:

WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: Date(timeIntervalSinceNow: TimeInterval(5) * 60), userInfo: nil, scheduledCompletion: self.scheduledCompletion)
Run Code Online (Sandbox Code Playgroud)

在哪里

func scheduledCompletion(error: Error?) {
        if error == nil { print("successfully scheduled application background refresh") }
        else { print("error scheduling background refresh, error: \(error)") }
}
Run Code Online (Sandbox Code Playgroud)

根据文档

scheduledCompletion 在后台应用程序刷新任务完成后由系统调用的块。

但是由于未知原因,它在调度后台刷新任务后被直接调用。后台刷新任务在正确的时间scheduledCompletion被调用,之后不会被调用。

那么它是文档中的错误,WatchKit 中的错误还是我做错了什么?

swift3 watchos-3 wkrefreshbackgroundtask

2
推荐指数
1
解决办法
2005
查看次数