Error when using Generic as property type in Swift

混江龙づ霸主 提交于 2019-12-30 06:44:21

问题


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() {
    }

}

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.xctoolc‌​hain/usr/bin/swift failed with exit code 

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

Edit - related: Swift compile error when subclassing NSObject and using generics

Update (6/18/14) - The issue still persists as of Xcode 6 - Beta 2

Update (7/25/14) - The issue still persists as of Xcode 6 - Beta 4 (thanks @Ralfonso, and I verified as well)

Update (8/4/14) - The issue is FIXED as of Xcode 6 - Beta 5!


回答1:


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() {
    }
}



回答2:


EDIT EDIT:

This is definitely a bug in the compiler.

I tried to 'outsmart' the compiler by using the following:

class TSSignal<TMessage>
{
    var messageType : Optional<TMessage> = nil

    init() { }
}

Same issue.




回答3:


This is NOT an "answer" (it is my own question), but I thought it worth noting what I did in this case to move passed this situation, for the time being.

import UIKit
class TSSignal {
    var message: AnyObject?
    init() {
    }
}

Lame, but I am sure it's only temporary.



来源:https://stackoverflow.com/questions/24193957/error-when-using-generic-as-property-type-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!