Swift-结构体

2018-01-15  本文已影响0人  qtoq126
  1. 结构体基础
struct Location {
    
    let latitude: Double
    let longtitude: Double
}

let appleHeadquartersLocation = Location(latitude: 37.3230, longtitude: -122.0322)
let googleHeadquartersLocation = Location(latitude: 37.4220, longtitude: -122.0841)

appleHeadquartersLocation.latitude
googleHeadquartersLocation.longtitude

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

let google = Place(location: googleHeadquartersLocation, name: "Google")
google.location.latitude
  1. 结构体构造函数
struct Location {
    
    let latitude: Double
    let longtitude: Double
    
    init?(coordinate: String) {

        //gurad关键字的妙用,注意如果说guard多个变量,每句末尾的都要有逗号
        guard
            let preIndex = coordinate.range(of: ",")?.lowerBound,
            let sufIndex = coordinate.range(of: ",")?.upperBound,
            let first = Double(coordinate.prefix(upTo: preIndex)),
            let second = Double(coordinate.suffix(from: sufIndex))
            else {
                return nil
            }
        
        self.latitude = first
        self.longtitude = second
    }
    
    func printLocation() {
        print("The location is \(latitude), \(longtitude)")
    }
}

var location = Location(coordinate: "321.33,-154.268")
location?.printLocation()
  1. 结构体内的函数
struct Location {
    
    let latitude: Double
    let longtitude: Double
    
    init?(coordinate: String) {
        
        guard
            let preIndex = coordinate.range(of: ",")?.lowerBound,
            let sufIndex = coordinate.range(of: ",")?.upperBound,
            let first = Double(coordinate.prefix(upTo: preIndex)),
            let second = Double(coordinate.suffix(from: sufIndex))
        else {
            return nil
        }
        
        self.latitude = firstIndex
        self.longtitude = secondIndex
    }
    
    func printLocation() {
        print("The location is \(latitude), \(longtitude)")
    }
}

var location = Location(coordinate: "321.334.268")
location!.printLocation()
  1. 重点

引用类型: Array、Set、Dictionary / String、Int、Float、Double、Bool
值类型:结构体(包括:Array、Set、Dictionary、String)、enum

上一篇 下一篇

猜你喜欢

热点阅读