Chapter 10: Structures
大綱
Introducing structures
struct Location {
let x: Int
let y: Int
}
struct DeliveryArea: CustomStringConvertible {
// sturct中可以再有個sturct
let center: Location
var radius: Double
var description: String {
return """
Area with center: x: \(center.x) - y: \(center.y),
radius: \(radius)
"""
}
// 定義method
func contains(_ location: Location) -> Bool {
let distanceFromCenter = distance(from: (center.x, center.y), to: (location.x, location.y))
return distanceFromCenter < radius
}
}
// Swift自動產生的Initializers, 會強制所有變數都有初始值
let storeLocation = Location(x: 2, y: 4)
var storeArea = DeliveryArea(center: storeLocation, radius: 4)Accessing members
Introducing methods
Structures as values
Structures everywhere
Conforming to a protocol
Key points
Last updated