Swift实现返回任意类型的函数及使用返回类型的报错问题求解
错误原因
- Swift 中泛型参数(比如
MemoryLayout<T>里的T)必须在编译期就确定具体类型,不能传入运行时才能得到的值。你代码里的returnType是运行时才生成的Any类型的元类型值,自然无法作为泛型参数使用,编译器找不到这个运行时的值对应的类型定义,就会报"Cannot find type 'returnType' in scope"的错误。
解决方案
方案1:把泛型操作挪到枚举分支直接处理
因为你的类型来源是固定的三个枚举case,直接在枚举匹配的分支里执行对应类型的MemoryLayout计算即可,不需要单独返回类型再二次处理:
private func getMemorySize() -> Int { switch self.someEnum { case .first: return MemoryLayout<UInt8>.size case .second: return MemoryLayout<UInt16>.size case .third: return MemoryLayout<UInt32>.size } }
使用时直接调用即可:
let size = self.getMemorySize()
方案2:运行时获取类型大小
如果确实需要先拿到返回的元类型再做通用计算,可以使用运行时方法代替泛型参数写法:
let returnType = self.getType() // 适配所有无参初始化的数值类型 if let valueType = returnType as? FixedWidthInteger.Type { let size = valueType.bitWidth / 8 }
方案3:编译期确定枚举场景用泛型实现
如果调用时可以在编译期确定枚举的取值,可以用泛型枚举实现编译期类型传递:
enum SomeEnum<T> { case first(T.Type = UInt8.self) case second(T.Type = UInt16.self) case third(T.Type = UInt32.self) } private func getType<T>(for enumCase: SomeEnum<T>) -> T.Type { switch enumCase { case .first(let t): return t case .second(let t): return t case .third(let t): return t } } // 调用时编译期就可以确定具体类型 let returnType = getType(for: .first()) let size = MemoryLayout<returnType>.size
内容的提问来源于stack exchange,提问作者Slavcho
相关产品推荐
相关产品推荐

