在 Swift 中使用 Generic 作为属性类型时出错 [英] Error when using Generic as property type in Swift
问题描述
我在使用泛型作为属性的类型约束时遇到问题.这是一个非常简单的例子:
I'm having an issue when using a Generic as the type constraint on a property. Here is a very simple example:
import UIKit
class TSSignal<MessageType> {
var message: MessageType?
init() {
}
}
在 Xcode 6 Beta (6A215l) 中,这不会编译.它失败并在底部出现以下错误:
In Xcode 6 Beta (6A215l) this will not compile. It fails with the following error at the bottom:
TSSignal.swift:13:9: error: unimplemented IR generation feature non-fixed class layout var message: MessageType? ^ LLVM ERROR: unimplemented IRGen feature! non-fixed class layout Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code
但是,如果我删除 var message: MessageType?
行,它会很好地构建.有任何想法吗?谢谢.
But, if I remove the line var message: MessageType?
it will build fine. Any ideas? Thanks.
编辑 - 更改代码和错误以反映问题的当前状态
Edit - changed code and error to reflect current status of issue
编辑 - 相关:子类化 NSObject 和使用泛型时 Swift 编译错误
更新 (6/18/14) - 从 Xcode 6 - Beta 2 开始,该问题仍然存在
Update (6/18/14) - The issue still persists as of Xcode 6 - Beta 2
更新 (7/25/14) - 从 Xcode 6 - Beta 4 开始,问题仍然存在(感谢 @Ralfonso,我也验证了)
Update (7/25/14) - The issue still persists as of Xcode 6 - Beta 4 (thanks @Ralfonso, and I verified as well)
更新 (8/4/14) - 从 Xcode 6 - Beta 5 开始,该问题已修复!
Update (8/4/14) - The issue is FIXED as of Xcode 6 - Beta 5!
推荐答案
有一个没有类型擦除的解决方法(适用于 Xcode6-Beta2):
There is a workaround without type erasure (works as of Xcode6-Beta2):
import UIKit
class TSSignal<MessageType> {
var _message: [MessageType] = []
func getMessage() -> MessageType? {
if _message.count > 0 {
return _message[0]
} else {
return nil
}
}
func setMessage(maybeMessage: MessageType?) {
if let message = maybeMessage {
_message = [message]
} else {
_message = []
}
}
init() {
}
}
这篇关于在 Swift 中使用 Generic 作为属性类型时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!