DevPrep

All topics › Programming basics

Instance variable (ivar)

Junior

Essence

An instance variable (ivar) is data that each object stores separately: two Person instances have their own name and age, and changing one does not touch the other. The term "ivar" comes from Objective-C; in Swift the same thing is called a stored property.

Objective-C: ivars and @property (legacy)

@interface Person : NSObject {
    NSString *_name;          // an ivar declared explicitly (old style)
}
@property (nonatomic, copy) NSString *email;  // the compiler synthesises _email
@end

Swift: stored and computed properties

final class Person {
    var name: String                      // stored property — Swift's "ivar"
    var email = ""                        // with a default value
    lazy var greeting = "Hi, \(name)"     // created on first access
    var initials: String { String(name.prefix(1)) }   // computed — no storage
    var age = 0 {
        didSet { print("age: \(oldValue) -> \(age)") }
    }
    init(name: String) { self.name = name }
}

let a = Person(name: "Ann"), b = Person(name: "Bob")
b.age = 30                 // age: 0 -> 30; a has its own set of properties
print(a.age, b.age)        // 0 30

How it differs from other variables

What the interviewer looks for

In an Objective-C context: the difference between _ivar and self.property and why init writes _name = name. In Swift: stored vs computed, lazy, observers, and the fact that a struct with let properties is fully immutable.

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