finish structure

This commit is contained in:
Gary Gan 2025-01-27 11:58:09 +08:00
parent 10812798ca
commit 719c9426fa
3 changed files with 102 additions and 0 deletions

View File

@ -0,0 +1,97 @@
import Foundation
// structure is a value type
struct Person {
let name: String
let age: Int
}
let foo = Person(name: "foo", age: 20)
foo.name
foo.age
struct CommodorComputer {
let name: String
let manufacturer: String = "Commodor"
// constructor
// init(name: String) {
// self.name = name
// self.manufacturer = "Commodor"
// }
}
let c64 = CommodorComputer(name: "Test")
c64.manufacturer
// Compute property
struct Person2 {
let firstName: String
let lastName: String
// let fullName: String
// init(firstName: String, lastName: String) {
// self.firstName = firstName
// self.lastName = lastName
// self.fullName = "\(firstName) \(lastName)"
// }
var fullName: String {
"\(firstName) \(lastName)"
}
}
let fooBar = Person2 (firstName: "Gary", lastName: "Gan")
fooBar.fullName
struct Car {
var currentSpeed: Int
mutating func drive(speed: Int) {
"Driving..."
currentSpeed = speed
}
}
let immutableCar = Car(currentSpeed: 10)
// !immutableCar.drive(speed: 20)
var mutableCar = Car(currentSpeed: 10)
mutableCar.drive(speed: 30)
mutableCar.currentSpeed
let copy = mutableCar
mutableCar.drive(speed: 40)
mutableCar.currentSpeed
copy.currentSpeed
struct LivingThing {
init() {
"I'm living"
}
}
//struct Animal: LivingThing {
//
//}
struct Bike {
let manufacturer: String
let currentSpeed: Int
func copy(currentSpeed: Int) -> Bike {
Bike (manufacturer: self.manufacturer, currentSpeed: currentSpeed)
}
}
let bike1 = Bike(manufacturer: "HD", currentSpeed: 20)
var bike2 = bike1.copy(currentSpeed: 40)
bike1.currentSpeed
bike2.currentSpeed

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='7.0' target-platform='macos' swift-version='6' buildActiveScheme='true' executeOnSourceChanges='true' importAppTypes='true'/>

View File

@ -1,6 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Structures.playground">
</FileRef>
<FileRef
location = "group:Closures.playground">
</FileRef>