Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using Generic as property type in Swift

Tags:

swift

xcode6

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!

like image 934
michaelavila Avatar asked Jun 12 '14 21:06

michaelavila


People also ask

What is generic constraints in Swift?

Generics in Swift allows you to write generic and reusable code, avoiding duplication. A generic type or function creates constraints for the current scope, requiring input values to conform to these requirements.

What is difference between generic and any Swift?

Generics and Any are often used for similar purposes, yet they behave very differently. In languages without generics, you typically use a combination of Any and runtime programming, whereas generics are statically checked at compile time.


1 Answers

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() {
    }
}
like image 105
Max Desiatov Avatar answered Oct 08 '22 05:10

Max Desiatov