Swift 自定义类型构建:结构与属性详解
1. 引言
在掌握 Swift 基础后,我们可以将所学知识整合,创建自定义类型。自定义类型能让我们用基础构建模块搭建大型复杂的程序。接下来将深入介绍结构和属性这两个重要概念。
2. 结构的引入
2.1 披萨店的例子
假设你在名为 Pizzaville 的小镇拥有一家名为“Swift Pizza”的披萨店。为了判断潜在顾客是否在配送范围内,最初的程序可能如下:
let restaurantLocation = (2, 4)
let restaurantRange = 2.5
// Pythagorean Theorem # $
func distance(from source: (x: Int, y: Int), to target: (x: Int, y: Int))
-> Double {
let distanceX = Double(source.x - target.x)
let distanceY = Double(source.y - target.y)
return sqrt(distanceX * distanceX + distanceY * distanceY)
}
func isInDeliveryRange(location: (x: Int, y: Int)) -> Bool {
let deliveryDistance = distance(from: location, to: restaurantLocation)
return deliv
超级会员免费看
订阅专栏 解锁全文
27

被折叠的 条评论
为什么被折叠?



