编辑代码

//结构体的定义
struct Book {
    var name = ""
    var price = 0
    var category = "common"
    func description() {
        print("\(name)'s price is \(price), category is \(category)")
    }
}
//结构体实例化
var theBook = Book(name: "Life of Pi", price: 62, category: "adventure")
print("\(theBook.name)'s category is \(theBook.category) and  price is \(theBook.price)RMB")
//访问结构体方法
let newBook = Book(name: "Life of Pi", price: 62, category: "adventure")
newBook.description()
//值类型
var anotherBook = theBook
print(theBook)
print(anotherBook)
anotherBook.category = "history"
anotherBook.price = 136
anotherBook.name = "Empiror Kangxi"
print(theBook)
print(anotherBook)
//结构体使用
struct Coordinate {
    let x : Double
    let y : Double
}
struct Line {
    let startPoint: Coordinate
    let endPoint: Coordinate
    func length() -> Double {
        let x = startPoint.x - endPoint.x
        let y = startPoint.y - endPoint.y
        return (x * x + y * y).squareRoot()
    }
}
let pointA = Coordinate(x: 1, y: 2)
let pointB = Coordinate(x: 3, y: 6)
let lineAB = Line(startPoint: pointA, endPoint: pointB)
print("The length of line AB is \(lineAB.length())")