- 结构体基础
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
- 结构体构造函数
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()
- 结构体内的函数
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()
- 重点
引用类型: Array、Set、Dictionary / String、Int、Float、Double、Bool
值类型:结构体(包括:Array、Set、Dictionary、String)、enum
网友评论