swift3-14 结构体

Swift 结构体是构建代码所用的一种通用且灵活的构造体。我们可以为结构体定义属性(常量、变量)和添加方法,从而扩展结构体的功能.
与 C 和 Objective-C 不同的是:

结构体总是通过被复制的方式在代码中传递,因此它的值是不可修改的.

示例

struct MarkStruct{
   var mark1: Int
   var mark2: Int
   var mark3: Int
}

结构体应用 需要注意的以下几点:

总的来说就是:结构体实例是通过值传递,而不是通过引用传递。

struct Location{
    var latitude:Double
    var longitude:Double
}
let aLocation = Location(latitude: 12.0,longitude: 212.0)
var bLoaction = Location.init(latitude: 1.2, longitude: 1.3)
struct Place{
    var location:Location
    var name:String
}

var aPlace = Place.init(location: bLoaction, name: "苹果总部")
bLoaction.latitude = 37.3230
bLoaction.longitude = -122.0332
print(aPlace)

构造函数

struct Location{
    var latitude : Double
    var longitude: Double

    init?(coordinateString:  String) {
         guard
            let commIndex = coordinateString.range(of: ","),
            let first = Double(coordinateString.substring(to: commIndex.lowerBound)),
            let second = Double(coordinateString.substring(from: commIndex.upperBound))
            else {
                return nil
        }

        self.latitude = first
        self.longitude = second
    }
    init(latitude:Double, longitude:Double) {
        self.latitude = latitude
        self.longitude = longitude

    }
    func printLocation() {
        print("The Location is \(self.latitude), \(self.longitude)")
    }
    func isNoth() -> Bool {
         self.printLocation()
         return self.latitude > 0
    }
}
let location = Location(coordinateString: "21,23")
location?.latitude
location?.longitude
let location2 = Location(latitude: 25.222,longitude: 122.23222)
location2.isNoth()