- 結(jié)構(gòu)體基礎(chǔ)
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
- 結(jié)構(gòu)體構(gòu)造函數(shù)
struct Location {
let latitude: Double
let longtitude: Double
init?(coordinate: String) {
//gurad關(guān)鍵字的妙用憨愉,注意如果說(shuō)guard多個(gè)變量,每句末尾的都要有逗號(hào)
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()
- 結(jié)構(gòu)體內(nèi)的函數(shù)
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()
- 重點(diǎn)
引用類(lèi)型: Array臂港、Set森枪、Dictionary / String视搏、Int、Float县袱、Double浑娜、Bool
值類(lèi)型:結(jié)構(gòu)體(包括:Array、Set式散、Dictionary筋遭、String)、enum