忍者刘米米

10. Classes and Structures

Comparing Classes and Structures

Item Class Structure
Define properties Yes Yes
Define methods Yes Yes
Define subscripts Yes Yes
Define initializers Yes Yes
Conform to protocols Yes Yes
extension Yes Yes
Inheritance Yes -
Type casting Yes -
Deinitializers Yes -
Objc-NSString or array YES -
Swift string or array - Yes
Memberwise Initializers - Yes
Reference counting allows more than one reference to a class instance always copied

Definition Syntax

  • give properties and methods lowerCamelCase names (such as frameRate and incrementCount)
  • Give class UpperCamelCase names (such asSomeClass and SomeStructure here)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class SomeClass {
// class definition goes here
}
struct SomeStructure {
// structure definition goes here
}

struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0

// a default value of nil
var name: String?
}

Class and Structure Instances

1
2
let someResolution = Resolution()
let someVideoMode = VideoMode()

Accessing Properties

dot syntax

Unlike Objective-C, Swift enables you to set sub-properties of a structure property directly.

1
2
3
4
5
6
7
8
9
print("The width of someResolution is \(someResolution.width)")
// Prints "The width of someResolution is 0"

print("The width of someVideoMode is \(someVideoMode.resolution.width)")
// Prints "The width of someVideoMode is 0"

someVideoMode.resolution.width = 1280
print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
// Prints "The width of someVideoMode is now 1280"

Memberwise Initializers for Structure Types

  • All structures have an automatically-generated memberwise initializer
  • Unlike structures, class instances do not receive a default memberwise initializer.
1
let vga = Resolution(width: 640, height: 480)

Structures and Enumerations Are Value Types

  • A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.
  • all of the basic types in Swift—integers, floating-point numbers, Booleans, strings, arrays and dictionaries—are value types, and are implemented as structures behind the scenes.
  • All structures and enumerations are value types in Swift. They can be copied with their value type property

Value type structure

1
2
3
4
5
6
7
8
9
10
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd

cinema.width = 2048

print("cinema is now \(cinema.width) pixels wide")
// Prints "cinema is now 2048 pixels wide"

print("hd is still \(hd.width) pixels wide")
// Prints "hd is still 1920 pixels wide"

Value type Enum

1
2
3
4
5
6
7
8
9
10
enum CompassPoint {
case north, south, east, west
}
var currentDirection = CompassPoint.west
let rememberedDirection = currentDirection
currentDirection = .east
if rememberedDirection == .west {
print("The remembered direction is still .west")
}
// Prints "The remembered direction is still .west"

Classes Are Reference Types

It is let not var, but you still can changed the value ,because It is the frameRate property of the underlying VideoMode that is changed, not the values of the constant references to that VideoMode.

1
2
3
4
5
6
7
8
9
10
11
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0

let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0

print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
// Prints "The frameRate property of tenEighty is now 30.0"

Identity Operators

check whether two constants or variables refer to the same single instance:

  • Identical to (===)
  • Not identical to (!==)
1
2
3
4
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}
// Prints "tenEighty and alsoTenEighty refer to the same VideoMode instance."

=== vs. ==

  • “Identical to” refer to exactly the same class instance.
  • “Equal to” means that two instances are considered “equal” or “equivalent” in value, for some appropriate meaning of “equal”, as defined by the type’s designer.

Pointers

Unlike C, C++, or Objective-C, Swift does not require you to write an asterisk (*) to indicate that you are creating a reference. Instead, these references are defined like any other constant or variable in Swift.

Choosing Between Classes and Structures

  • structure instances are always passed by value, and class instances are always passed by reference.
  • In practice, most custom data constructs should be classes, not structures.

When to use structures

  • Encapsulate a few relatively simple data values.
  • Encapsulated values will be copied rather than referenced
  • Any properties stored by the structure are themselves value types
  • The structure does not need to inherit properties or behavior from another existing type.

Example of structures

  • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
  • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
  • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

Assignment and Copy Behavior for Strings, Arrays, and Dictionaries

Swift

String, Array, and Dictionary are implemented as structures, they can be copied.

Objective - C

NSString, NSArray, and NSDictionary are implemented as classes, not structures. Strings, arrays, and dictionaries in Foundation are always assigned and passed around as a reference to an existing instance, rather than as a copy.