What's the opposite of AnyObject?

So we have AnyObject to (among other things) say that only classes can conform to a protocol. What do I do if I have a protocol that should only be usable by value types?

1 Like

This protocol does not exist, and yet it has been discussed many times in this forum. It looks like there are a lot of conflicting definitions of what a "value type" is, so nothing conclusive has ever emerged. Those threads are an interesting read.

Practically speaking, you may get more targeted advice if you tell what is your goal.


Every type in Swift is a value type. But not all members of the type are part of its value. The type itself defines what “value” means for it.

For classes, 32/64 bits of reference is part of the value, but the data they are pointing to is not.

For correctly implemented type, it’s value should be what is compared by ==, and it should be a subset of things that do not change for let-declarations.

But currently there is no way in the language to declare which members are part of the value, and no way for compiler to check that implementation matches this declaration.

The only tools at your disposal here are code comments and a team of “consenting adults”

protocol P {
    var foo: Int { get set } // Mutating set, we want this to be part of the value

class C: P {
    var foo: Int = 42

let c = C()
let p: P = c
p.foo += 1 // error, we cannot change it on let declaration, that’s good
c.foo += 1 // but someone else can (((

// Normally we think of Int as being a value type, but it can always be used as a reference type
extension Int: P {
    private static data: [Int: Int] = [:]

    var foo: Int {
        get { Self.data[self] ?? 0 }
        nonmutating set { Self.data[self] = newValue }
Terms of Service

Privacy Policy

Cookie Policy