【问题标题】:Function for returning any type Swift [duplicate]返回任何类型 Swift 的函数
【发布时间】:2021-11-12 00:10:01
【问题描述】:

我想要一个函数,该函数将返回一个类型,然后再使用该类型。

例如:

private func getType() -> Any {
    switch self.someEnum {
    case .first:
        return UInt8.self
    case .second:
        return UInt16.self
    case .third:
        return UInt32.self
    }
}

然后是要使用的结果

let returnType = self.getType()
MemoryLayout<returnType>.size

当我使用这个时,我得到了这个错误“在范围内找不到类型'returnType'”。

【问题讨论】:

  • 您想在任意上下文中使用类型变量,还是只是调用MemoryLayout
  • 专门针对MemoryLayout,所以我只接受下面的答案。
  • 有一种方法可以使用 Swift 元数据。如果你愿意,我可以重新打开这个问题并以这种方式回答。

标签: ios swift


【解决方案1】:

为什么不简化问题,直接从enum返回一个size

enum SomeEnum {
    case first
    case second
    case third
}

extension SomeEnum {
    func getSize() -> Int {
        switch self {
        case .first:
            return MemoryLayout<UInt8>.size
        case .second:
            return MemoryLayout<UInt16>.size
        case .third:
            return MemoryLayout<UInt32>.size
        }
    }
}

因此,如果您有一个带有该枚举的类,作为成员,您可以将其用作

someEnum.getSize()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多