枚举以及可选项

This commit is contained in:
2021-12-05 21:18:35 +08:00
parent 725918c297
commit 8af44f0613
4 changed files with 322 additions and 0 deletions

View File

@@ -0,0 +1,138 @@
//: [Previous](@previous)
import Foundation
var greeting = "Hello, playground"
//: ####
//
enum Direction {
case north
case south
case east
case west
}
// 访
var dir = Direction.north
dir = Direction.east
dir = .north
print(dir)
//: #### Associated Values
//
enum Score {
case points(Int)
case grade(Character)
}
var score = Score.points(96)
score = .grade("A")
//: #### Raw Value
// 使
enum PokerSuit : Character { //
case spade = "♠️"
case heart = "♥️"
case dismand = "♦️"
case club = "♣️"
}
var suit = PokerSuit.spade
print(suit)
print(suit.rawValue) //
//: #####
/*:
IntStringSwift
- Int0
- String
*/
//: #### MemoryLayout
/*:
MemoryLayoutsizestridealignment
- size: . Size is the number of bytes to read from the pointer to reach all the data.
- stride: Stride is the number of bytes to advance to reach the next item in the buffer.The stride determines the distance between two elements, which will be greater than or equal to the size.
- alignmentThe alignment of a struct type is the maximum alignment out of all its properties.Alignment is the the evenly divisible by number that each instance needs to be at.
*/
var age = 18
MemoryLayout.size(ofValue: age)
MemoryLayout.alignment(ofValue: age)
MemoryLayout.stride(ofValue: age)
enum Password {
case other
case number(Int, Int, Int, Int)
}
MemoryLayout<Password>.size
MemoryLayout<Password>.stride
MemoryLayout<Password>.alignment
/*:
1. Puppy8Int
2. 8
3. Puppy
-----------------------------------------------------------------
|...|...|...|...|...|...|...|...|...| | | | | | | |
|...|...|...|...|...|...|...|...|...| | | | | | | |
|...|...|...|...|...|...|...|...|...| | | | | | | |
-----------------------------------------------------------------
Int Bool
|-----------> <----------|---|
// Size is the number of bytes to read from the pointer to reach all the data.
|-------------> size <--------------|
size = 9
*/
struct Puppy {
let age: Int
let isTrained: Bool
} // Int, Bool
MemoryLayout<Puppy>.size
MemoryLayout<Puppy>.stride
MemoryLayout<Puppy>.alignment
/*:
1. AlternatePuppy8Int
2. 8
3. AlternatePuppy
-----------------------------------------------------------------
|...| | | | | | | |...|...|...|...|...|...|...|...|
|...| | | | | | | |...|...|...|...|...|...|...|...|
|...| | | | | | | |...|...|...|...|...|...|...|...|
-----------------------------------------------------------------
|----------> Bool <----------|----------> Int <-----------|
// Size is the number of bytes to read from the pointer to reach all the data.
|---------------------------> size <----------------------------|
size = 16
*/
struct AlternatePuppy {
let isTrained: Bool
let age: Int
} // Bool, Int
MemoryLayout<AlternatePuppy>.size
MemoryLayout<AlternatePuppy>.stride
MemoryLayout<AlternatePuppy>.alignment
//: [Next](@next)