Skip to content

Commit 3a1b50e

Browse files
committed
Merge pull request kodecocodes#58 from gregheo/issue-58
Merge in Matthijs's struct vs classes
2 parents 1bb8fec + b6804f2 commit 3a1b50e

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

README.markdown

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,16 @@ Avoid block comments inline with code, as the code should be as self-documenting
142142

143143
## Classes and Structures
144144

145+
### Which one to use?
146+
147+
Remember, structs have [value semantics](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_144). Use structs for things that do not have an identity. An array that contains [a, b, c] is really the same as another array that contains [a, b, c] and they are completely interchangeable. It doesn't matter whether you use the first array or the second, because they represent the exact same thing. That's why arrays are structs.
148+
149+
Classes have [reference semantics](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_145). Use classes for things that do have an identity or a specific life cycle. You would model a person as a class because two person objects are two different things. Just because two people have the same name and birthdate, doesn't mean they are the same person. But the person's birthdate would be a struct because a date of 3 March 1950 is the same as any other date object for 3 March 1950. The date itself doesn't have an identity.
150+
151+
Sometimes, things should be structs but need to conform to `AnyObject` or are historically modeled as classes already (`NSDate`, `NSSet`). Try to follow these guidelines as closely as possible.
152+
153+
### Example definition
154+
145155
Here's an example of a well-styled class definition:
146156

147157
```swift

0 commit comments

Comments
 (0)