barndog
barndog

Reputation: 7173

Swift Variable Constraints

Is it possible in the current iteration of Swift (2.1) to add constraints on a variable type?

If I have a class Element

class Element: NSObject {
    var type: ElementType
    init(type: ElementType) {
        self.type = type
    }
}

with an enum ElementType

enum ElementType {
    case Cell
    case Header
    case Footer
    case Decoration(kind: String)
}

in some other class if I have a variable of type Element, is it at all possible to put constraints like:

var element: Element? where Self == .Header

or instead would I have to override didSet

var element: Element? {
    didSet {
        if let value = element where value.type == Decoration {
            element = Optional.None
        }
    }
}

I'm sure it's not possible, the generic system isn't as powerful as I would like (being able to only constrain extensions by protocol and class inheritance for example and no variadic generic parameters).

Upvotes: 1

Views: 1012

Answers (1)

Sulthan
Sulthan

Reputation: 130102

Type constraints and types checks are a compilation feature but you want to check the runtime value of an object.

I am pretty sure that's impossible. You will have to use a runtime check (e.g. willSet or didSet).

Or, instead of enforcing the type by the value of a type atrribute, enforce it with a real type, e.g.

subclassing

class Header: Element

or make Element a protocol implemented by four separate classes:

protocol Element {
}

class Header: Element

(you can use protocol extension for shared functions).

Upvotes: 2

Related Questions