14 Swift 结构体

2017-07-05  本文已影响65人  猴子的救兵520

结构体的介绍

struct 结构体名称 {
    // 属性和方法
}

结构体的增强

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")
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)
extension Location {
    mutating func moveH(x : Double) {
        self.x += x
    }

    mutating func moveV(y : Double) {
        self.y += y
    }
}
上一篇下一篇

猜你喜欢

热点阅读