struct Location {
var x : Double
var y : Double
init(x : Double, y : Double) {
self.x = x
self.y = y
}
init(xyString : String) {
let strs = xyString.components(separatedBy: ",")
x = Double(strs.first!)!
y = Double(strs.last!)!
}
}
let location = Location(x: 100, y: 100)
let location1 = Location(xyString: "101,101")
为结构体扩充方法
为了让结构体使用更加灵活,swift的结构体中可以扩充方法
例子:为Location结构体扩充两个方法
向水平方向移动的方法
向垂直方向移动的方法
struct Location {
var x : Double
var y : Double
init(x : Double, y : Double) {
self.x = x
self.y = y
}
init(xyString : String) {
let strs = xyString.components(separatedBy: ",")
x = Double(strs.first!)!
y = Double(strs.last!)!
}
mutating func moveH(x : Double) {
self.x += x
}
mutating func moveV(y : Double) {
self.y += y
}
}
var location = Location(x: 100, y: 100)
print(location) // Location(x: 100.0, y: 100.0)
location.moveH(x: 30)
location.moveV(y: -10)
print(location) // Location(x: 130.0, y: 90.0)