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

Swift Structs

Swift Structs

A structure (struct) is the most commonly used custom type in Swift, used to bundle a group of related data together.

It looks similar to a class, but the essential difference is that a struct is a value type while a class is a reference type.

This article first covers the definition, instantiation, and memberwise initializer of structs, then focuses on clearing up the widespread misconception that "a struct's values cannot be modified", and finally uses a table to lay out the differences between structs and classes once and for all.


Definition and instantiation

Define a struct with the struct keyword, write properties inside the braces, and then call its initializer to create an instance.

Example

// Define a struct that describes a website

struct

RunoobSite

{

    var name

:

String    

// Website name

    var url

:

String    

// Website address

    var year

:

Int      

// Year founded

}

// Create an instance with the auto-generated initializer

var site

=

RunoobSite

(

name

:

"Runoob"

, url

:

"www.runoob.com"

, year

:

2014

)

print

(

site.

name

)

print

(

site.

url

)

// Access and modify properties with dot syntax

site.

year

=

2026

print

(

site.

year

)



Runoob

www.runoob.com

2026

Struct names use UpperCamelCase and property names use lowerCamelCase; this is the common practice in the Swift community.


Memberwise Initializer

As long as the struct does not define its own initializer, Swift automatically generates a memberwise initializer, with parameters in the same order as the property declarations.

If a property has a default value, the corresponding parameter can be omitted at the call site.

Example

struct

RunoobPoint

{

    var x

:

Int

    var y

:

Int

}

// Memberwise initializer: parameter names are the property names

let p

=

RunoobPoint

(

x

:

3

, y

:

4

)

print

(

p.

x

, p.

y

)

struct

RunoobCourse

{

    var title

:

String

    var lessons

:

Int

=

43

 

// Has a default value, can be omitted at the call site

}

let course

=

RunoobCourse

(

title

:

"Swift Tutorial"

)

print

(

course.

title

, course.

lessons

)

// When all properties have default values, you do not even need to write any parameters

struct

RunoobDefaults

{

    var name

=

"RUNOOB"

    var visits

=

0

}

print

(

RunoobDefaults

(

)

.

name

)



3 4

Swift 教程 43

RUNOOB

Note:If you write an initializer inside the struct by hand, the auto-generated memberwise initializer disappears. Putting the custom initializer in an extension lets you keep both.

Example

struct

RunoobSize

{

    var width

:

Int

    var height

:

Int

}

// The initializer is written in an extension, and the memberwise initializer remains available

extension RunoobSize

{

    init

(

side

:

Int

)

{

        self.

init

(

width

:

side, height

:

side

)

   

}

}

print

(

RunoobSize

(

width

:

10

, height

:

20

)

.

width

)

 

// Use the memberwise initializer

print

(

RunoobSize

(

side

:

5

)

.

height

)

             

// Use the initializer in the extension



10

5


A Struct's Properties Can Be Modified

Many older resources say "structs are passed by value, so their values cannot be modified", and this statement is wrong.

Whether a struct instance can be modified depends only on how it is declared: one declared with var can be changed, while one declared with let cannot.

Example

struct

RunoobSite

{

    var name

:

String

    var year

:

Int

}

// A struct instance declared with var can have its properties freely modified

var site

=

RunoobSite

(

name

:

"Runoob"

, year

:

2014

)

site.

year

=

2026

print

(

site.

year

)

// A struct instance declared with let cannot have any properties modified

let fixed

=

RunoobSite

(

name

:

"RUNOOB"

, year

:

2014

)

// fixed.year = 2026 // compile error: cannot assign to property

print

(

fixed.

year

)



2026

2014

For a struct instance declared with let, even calling methods that modify itself (mutating methods) is not allowed.

Note:Value type and mutability are two different things. A value type means "each variable holds its own copy", not "cannot be modified". For the mutating usage related to methods, see article 18 《Swift Methods》。


Value Semantics

Assigning a struct instance to another variable, or passing it as a parameter to a function, both involve copying; the two variables each hold an independent set of data.

Example

struct

RunoobPoint

{

    var x

:

Int

    var y

:

Int

}

var p1

=

RunoobPoint

(

x

:

1

, y

:

2

)

var p2

=

p1        

// Copy out an independent duplicate

p2.

x

=

100

       

// Only modify p2

print

(

p1.

x

, p2.

x

)

 

// p1 is completely unaffected



1 100

This kind of copy is "deep": if another struct is nested inside the struct, modifying an inner property of the copy will not affect the original instance either.

Example

struct

RunoobPoint

{

    var x

:

Int

    var y

:

Int

}

struct

RunoobTeam

{

    var leader

:

RunoobPoint  

// A nested struct

}

var t1

=

RunoobTeam

(

leader

:

RunoobPoint

(

x

:

1

, y

:

1

)

)

var t2

=

t1

t2.

leader

.

x

=

99

             

// Modify the nested value in the copy

print

(

t1.

leader

.

x

, t2.

leader

.

x

)



1 99

The benefit of value semantics is predictable behavior: no matter how a function modifies a struct parameter, it will not pollute the caller's data.

The cost is that copying has overhead when the data is large; Swift optimizes standard library types such as arrays and dictionaries with copy-on-write (COW), and for details see article 32 《Swift Value Semantics and Copy-On-Write》。


Comparing Structs and Classes

Structs and classes are highly similar in syntax; both can define properties, methods, subscripts, and initializers, and both can conform to protocols, but their underlying models are completely different.

The table below collects the key differences between the two; article 16 《Swift Classes》 covers only the class-specific parts and does not repeat this table.

Comparison Item Struct (struct) Class (class)
Nature of the type value types Reference type
Assignment and parameter passing Copies out an independent duplicate Copies the reference, with multiple variables pointing to the same instance
Memory management Does not involve reference counting Managed by ARC, with reference counting overhead
inheritance Does not support inheritance Supports inheritance and overriding
Constructor Automatically gets a memberwise initializer Must write init yourself or give all properties default values
Deinitialization No deinit Has deinit, executed before the instance is destroyed
Identity comparison Use == to compare contents, requires Equatable conformance Use === to determine whether it is the same instance
Mutability var instances can be modified, let instances are completely immutable a let reference can still modify the var properties of the instance it points to
Applicable scenarios Small data such as data models, coordinates, and configuration When shared state, inheritance, or polymorphism is needed

The official default recommendation is: prefer structs, and switch to classes only when reference semantics, inheritance, or lifetime management is genuinely needed.


Common questions

Below are the most common questions about using structs.

Can a struct have methods

Yes. A struct can define instance methods and type methods, conform to protocols, and implement subscripts; functionally it is almost the same as a class, except that it cannot inherit.

When a method needs to modify a property internally, you must add the mutating keyword to the method.

Why does the original struct also change when I modify the copy

If the struct stores a reference type (such as a class instance), the copy holds the same reference, so when the object pointed to by the reference is changed, both sides will see the change.

This is a typical pitfall of nesting reference types inside value types; to judge, look at whether the specific property is a value type or a reference type.

Can structs be compared for equality

Once a struct conforms to the Equatable protocol, it can be compared with ==. When all stored properties conform to Equatable, the compiler can synthesize the implementation automatically without writing it by hand.

Classes can also use ==, but that compares contents; to determine whether it is the same instance, you must use ===.