【问题标题】:AbsoluteTime type not imported into SwiftAbsoluteTime 类型未导入 Swift
【发布时间】:2016-08-17 12:50:58
【问题描述】:

在尝试对 IOKit HID 代码使用 AbsoluteTime 类型时,Swift 编译器似乎很困惑。

这个块编译和运行良好,打印“UnsignedWide”。

import IOKit.hid

var event = IOHIDEventStruct()
let timestamp = event.timestamp
let lo: UInt32 = timestamp.lo
let hi: UInt32 = timestamp.hi
let newTime = event.timestamp.dynamicType.init(lo: lo, hi: hi)
event.timestamp = newTime
print(timestamp.dynamicType)

但是,这不会编译。

let time1: AbsoluteTime = event.timestamp

"error: use of undeclared type 'AbsoluteTime'"

这也无法编译。

let wide1: UnsignedWide = event.timestamp

"error: use of undeclared type 'UnsignedWide'"

这也无法编译,但这是意料之中的。

let uint: UInt64 = event.timestamp

"error: cannot convert value of type 'AbsoluteTime' (aka 'UnsignedWide') to specified type 'UInt64'"

因此,由于 Swift 清楚地知道 UnsignedWide 是一个具有两个 UInt32 字段的结构,我想我会尝试使用这些特性定义我自己的结构,但这也失败了。

struct UnsignedWide {
    let lo: UInt32
    let hi: UInt32
}
typealias AbsoluteTime = UnsignedWide
let time2: AbsoluteTime = event.timestamp
let wide2: UnsignedWide = event.timestamp

"error: cannot convert value of type 'AbsoluteTime' (aka 'UnsignedWide') to specified type 'AbsoluteTime' (aka 'UnsignedWide')" 
"error: cannot convert value of type 'AbsoluteTime' (aka 'UnsignedWide') to specified type 'UnsignedWide'"

至少这是可行的。

let time3: AbsoluteTime = unsafeBitCast(event.timestamp, AbsoluteTime.self)

不过我不想那样做,我只能用这种丑陋的方式创建 AbsoluteTime 变量。

let AbsoluteTime = event.timestamp.dynamicType
let time4 = AbsoluteTime.init(lo: lo, hi: hi)

不幸的是,这不允许我使用 AbsoluteTime 作为函数或结构或类似的类型,所以这并不能真正解决我的问题。

Xcode 7.3 和 Xcode 7.3.1 GM 就是这种情况。

有人知道解决办法吗?

【问题讨论】:

  • 在我看来是个错误。

标签: xcode swift types compiler-errors iokit


【解决方案1】:

使用Darwin.UnsignedWide,别名为AbsoluteTime

例如:

这样编译:

import Darwin

public protocol CurrentAbsoluteTimeProvider: class {
    func currentAbsoluteTime() -> Darwin.AbsoluteTime
}

编译失败:

import Darwin

public protocol CurrentAbsoluteTimeProvider: class {
    func currentAbsoluteTime() -> AbsoluteTime
}

我已将此文件添加到使用 IOKit 的库中:https://github.com/avito-tech/Mixbox/blob/e3a5991f61dd2a36e13193e67ca69743f5bb62c7/Frameworks/Foundation/CurrentAbsoluteTimeProvider/AbsoluteTime/AbsoluteTime.swift

顺便说一句,我们公司正在开发一个用于 IOKit 的 Swift 库。固定链接:https://github.com/avito-tech/Mixbox/tree/e3a5991f61dd2a36e13193e67ca69743f5bb62c7/Frameworks/IoKit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-17
    • 2013-12-02
    • 1970-01-01
    • 2016-05-15
    • 2018-01-13
    • 1970-01-01
    • 2014-08-12
    • 2016-10-21
    相关资源
    最近更新 更多