Swift 2 学习笔记 11.结构体

课程来自慕课网liuyubobobo老师


结构体
  • 结构体基础
struct Location{
    let latitude: Double
    let longitude: Double
}

let appleHeadQuarterLocation: Location = Location(latitude: 37.3230, longitude: -122.0322)

struct Place {
    let location: Location
    var name: String
}

var appleHeadQuarter = Place(location: appleHeadQuarterLocation, name: "Apple")
appleHeadQuarter.location.latitude  // 37.323
  • 结构体之构造函数
struct Location{
    let latitude: Double
    let longitude: Double
    var placeName: String?
    
    init(coordinateString: String) {
//        let preIndex = coordinateString.range(of: ",")!.lowerBound
//        let sufIndex = coordinateString.range(of: ",")!.upperBound
//        self.latitude = Double(coordinateString.prefix(upTo: preIndex)) ?? 0
//        self.longitude = Double(coordinateString.suffix(from: sufIndex)) ?? 0
        
        let commaIndex = coordinateString.index(of: ",")!
        self.latitude = Double(coordinateString[..
  • 结构体之可失败的构造函数
struct Location{
    let latitude: Double
    let longitude: Double
    var placeName: String?
    
    init?(coordinateString: String) {
        if let commaIndex = coordinateString.index(of: ","){
            self.latitude = Double(coordinateString[..
  • 在结构体和枚举中定义方法
struct Location{
    let latitude: Double
    let longitude: Double
    var placeName: String?
    
    init?(coordinateString: String) {
        if let commaIndex = coordinateString.index(of: ","){
            self.latitude = Double(coordinateString[..
  • 结构体和枚举是值类型
struct Point {
    var x = 0
    var y = 0
}

var p1 = Point()
var p2 = p1

p1.x += 1
p1.x  // 1
p2.x  // 0
  • 随处可见的结构体
// Array, Dictionary, Set 都是结构体
// Int, Float, Double, Bool, String 都是结构体