iOS二次发育(swift)结构体
struct Location{ var latitude: Double = 0 var longitude: Double = 0 //使用Failable-Initializer init?(coordinateString: String) { if let commaIndex = coordinateString.range(of: ","){ if let firstElement = Double(coordinateString.substring(to: commaIndex.lowerBound)){ if let secondElement = Double(coordinateString.substring(from: commaIndex.upperBound)){ self.latitude = firstElement self.longitude = secondElement }else{ return nil } }else{ return nil } }else{ return nil } } init(latitude: Double, longitude: Double) { self.latitude = latitude self.longitude = longitude } init?(coordinateString2: String) { guard let commaIndex = coordinateString2.range(of: ",") else { return nil } guard let firstElement = Double(coordinateString2.substring(to: commaIndex.lowerBound)) else { return nil } guard let secondElement = Double(coordinateString2.substring(from: commaIndex.upperBound)) else { return nil } self.latitude = firstElement self.longitude = secondElement } } let appleHeadQuarterLocation = Location(coordinateString: "12,33") let appleHeadQuarterLocation2 = Location(latitude: 44, longitude: 55) let appleHeadQuarterLocation3 = Location(coordinateString2: "12?33")
结构体函数自己修改自己需要加mutating关键字
struct Location{ var x = 0 var y = 0 mutating func goEast() { self.x += 1 } }
如果结构体对所有存储型属性提供了默认值且自身没有提供定制的构造器,它们能自动获得一个逐一成员构造器。
struct Rectangle { //var length = 100.0, breadth = 200.0 var length: Double, breadth: Double } //let area = Rectangle(length: 1.1, breadth: 2.2) let area = Rectangle(length: 3.3, breadth: 4.4)