DevPrep

All topics › The Swift Language

Can you use @objc on a struct? Why not?

Middle PRO

The idea

No. @objc makes a member visible to the Objective-C runtime, and that runtime only works with objects: an isa pointer to the class, the class method table, selector lookup via objc_msgSend. A struct has none of this — it is a value type that lives directly on the stack or inside another value, is copied bitwise and has no identity. The compiler says exactly that: '@objc' can only be used with members of classes, @objc protocols, and concrete extensions of classes.

import Foundation

struct Point { var x = 0.0, y = 0.0 }
// @objc struct Point {}            // error: '@objc' can only be applied
//                                  //        to classes
// struct S { @objc func f() {} }   // error: '@objc' can only be used
//                                  //        with members of classes...

final class PointBox: NSObject {    // bridge for Obj-C: wrap it in a class
    let point: Point
    init(_ point: Point) { self.point = point }
    @objc var x: Double { point.x }
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store