Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Classes

Swift Classes

A class (class) is another custom type in Swift; the biggest difference from a struct is that it is a reference type.

The same class instance can be referenced by several variables at once; modifying it through any one variable is visible to all the others.

This article covers defining and instantiating classes, reference semantics, identity operators, and the two class-modifying keywords final and open.


Definition and instantiation

Define a class with the class keyword; properties are written the same way as in a struct.

Unlike structs, classes do not automatically get a memberwise initializer, so every stored property must have an initial value: either a default value at declaration or an assignment in init.

Example

// Properties have no default values; you must write init to assign them

class

RunoobSite

{

    var name

:

String

    var url

:

String

    init

(

name

:

String, url

:

String

)

{

        self.

name

=

name

        self.

url

=

url

   

}

}

let site

=

RunoobSite

(

name

:

"Runoob"

, url

:

"www.runoob.com"

)

print

(

site.

name

)

// When all properties have default values, init can be omitted

class

RunoobCourse

{

    var title

=

"Swift Tutorial"

    var lessons

=

43

}

let course

=

RunoobCourse

(

)

print

(

course.

title

, course.

lessons

)



Runoob

Swift 教程 43

If you provide neither default values nor an init, compilation fails immediately — a property may not be left uninitialized.

Example

// The following does not compile:

//

// class RunoobBad {

// var name: String // Compile error: class 'RunoobBad' has no initializers

// }

Note:A struct automatically gets a memberwise initializer when no initializer is written; a class gets no such treatment. Class initialization is more complex, involving designated initializers, convenience initializers, and inheritance rules; see article 20, "Swift Initialization》。


Reference semantics

Assigning a class instance to another variable copies the reference, not the object itself; both variables point to the same instance on the heap.

Example

class

RunoobCourse

{

    var title

=

"Swift Tutorial"

    var lessons

=

43

}

let a

=

RunoobCourse

(

)

let b

=

a                  

// b and a point to the same instance

b.

lessons

=

50

           

// Modify through b

print

(

a.

lessons

, b.

lessons

)

// a also sees the change



50 50

Note that a is declared with let, yet you can still modify the properties of the instance it points to.

Because let restricts only that "a cannot point to another instance", not that "the inside of the instance cannot change".

Note:Instances of reference types live on the heap and have their lifetime managed automatically by ARC; for the specific rules, see article 33, "Swift Automatic Reference Counting》。


Identity operators === and !==

=== checks whether two variables point to the same instance; !== checks whether they do not.

They compare "identity", not "content".

Example

class

RunoobCourse

{

    var title

=

"Swift Tutorial"

    var lessons

=

43

}

let a

=

RunoobCourse

(

)

let b

=

a

print

(

a

===

b

)

     

// true, the same instance

let c

=

RunoobCourse

(

)

print

(

a

===

c

)

     

// false, same content but two different instances

print

(

a

!

==

c

)

     

// true



true

false

true

Classes have no == by default; to compare by content, make the class conform to Equatable and implement the comparison logic yourself.

operator What is compared Applicable to types
=== Whether two references point to the same instance Class instances (AnyObject)
!== Whether two references point to different instances Class instances (AnyObject)
== Whether the contents of two values are equal Types conforming to Equatable

final and open

final means "stop here; no further inheritance or overriding", while open means "other modules are welcome to inherit and override".

final can be applied to a class, or to just a single method or property.

Example

// A final class cannot be subclassed

final

class

RunoobConfig

{

    var host

=

"www.runoob.com"

}

// The following line causes a compile error: inheritance from a final class

//

// class RunoobSubConfig: RunoobConfig {}

let config

=

RunoobConfig

(

)

print

(

config.

host

)

// final can also modify a single method

class

RunoobBase

{

    final func run

(

)

{

        print

(

"This method cannot be overridden by subclasses"

)

   

}

    func other

(

)

{

        print

(

"This method can be overridden"

)

   

}

}



www.runoob.com

open can only be used on classes and members accessible from other modules; it carries one more meaning than public: allowing cross-module inheritance and overriding.

Example

open

class

RunoobBase

{

    open func runoob

(

)

{

         

// Other modules can inherit and override

        print

(

"Superclass implementation"

)

   

}

    func helper

(

)

{

             

// Can only be overridden within the current module

        print

(

"Visible within the module"

)

   

}

}

class

RunoobSub

:

RunoobBase

{

    override func runoob

(

)

{

        print

(

"Subclass override"

)

   

}

}

let sub

=

RunoobSub

(

)

sub.

runoob

(

)



子类重写

Modifiers Scope Description
final The current class or member Forbids inheritance and overriding; the compiler may also perform extra optimizations
open Across modules Allows other modules to inherit the class and override members; implies public

Note:final and open cannot be used together. For the general form of inheritance and overriding, see article 22, "Swift Inheritance", and for the full set of access control levels, see article 39, "Swift Access Control》。


Guidelines for choosing between classes and structs

The official documentation's default advice is to prefer structs and switch to a class only when you genuinely need class features.

The full comparison table between structs and classes is in article 15, "Swift Structs"; here only practical, scenario-based advice is given.

Scenario Recommendation Reason
Just bundling a few properties together, such as coordinates, configuration, or data returned by an API Structure Value semantics keep data flow clear and prevent accidental modification
Multiple holders need to see the same state, such as a shared cache or connection pool class Reference semantics guarantee that everyone operates on the same object
Need inheritance for polymorphism, or already have a superclass class Structs do not support inheritance
Need to release resources or unregister notifications when the instance is destroyed class Only classes have deinit; see article 21, "Swift Deinitialization》
Need interoperability with Objective-C, such as subclassing NSObject class Objective-C's type system is class-based
Need an automatically generated memberwise initializer Structure Classes do not generate one automatically
The object is large, copying is noticeably expensive, and no copy is needed anyway class Passing by reference does not copy the content

In the standard library, String, Array, Dictionary, and Set are all structs, while objects like URLSession that need to manage lifetime and shared state are classes.


Common questions

Here are the most frequently asked questions about using classes.

Why must a class have init or default values?

A class's stored properties must all be initialized before init returns; this is a hard compiler check.

Giving a property a default value is also a form of initialization, so when all properties have default values, Swift provides a parameterless default init.

Why can properties of a class instance declared with let still be changed?

let restricts the reference itself, preventing it from pointing to another instance; whether a var property inside the instance can be changed is determined by that property's own declaration.

To prevent external modification of a property, declare it as let or restrict write access with private(set).

When should you add final?

Add it whenever there is no need for inheritance. final tells the compiler that no subclass will override, eliminating dynamic dispatch overhead and clearly expressing the class's design intent.

The cost is that you must revisit it if inheritance is genuinely needed later, so be cautious when designing a framework's public types; in ordinary business code, adding final is very common.