课程来自慕课网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[..<commaIndex]) ?? 0
self.longitude = Double(coordinateString[coordinateString.index(after: commaIndex)..<coordinateString.endIndex]) ?? 0
}
init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
}
init(latitude: Double, longitude: Double, placeName: String) {
self.latitude = latitude
self.longitude = longitude
self.placeName = placeName
}
}
let location = Location(coordinateString: "37.3230,-122.0322")
let location2 = Location(latitude: 37.3230, longitude: -122.0322)
let location3 = Location(latitude: 37.3220, longitude: -122.0322, placeName: "Apple Head Quarter")
- 结构体之可失败的构造函数
struct Location{
let latitude: Double
let longitude: Double
var placeName: String?
init?(coordinateString: String) {
if let commaIndex = coordinateString.index(of: ","){
self.latitude = Double(coordinateString[..<commaIndex]) ?? 0
self.longitude = Double(coordinateString[coordinateString.index(after: commaIndex)..<coordinateString.endIndex]) ?? 0
}else {
return nil
}
}
}
let location = Location(coordinateString: "37.3230&-122.0322") // nil
- 在结构体和枚举中定义方法
struct Location{
let latitude: Double
let longitude: Double
var placeName: String?
init?(coordinateString: String) {
if let commaIndex = coordinateString.index(of: ","){
self.latitude = Double(coordinateString[..<commaIndex]) ?? 0
self.longitude = Double(coordinateString[coordinateString.index(after: commaIndex)..<coordinateString.endIndex]) ?? 0
}else {
return nil
}
}
func printLocation() {
print(self.latitude)
print(self.longitude)
}
}
let location = Location(coordinateString: "37.3230,-122.0322")
location?.printLocation()
- 结构体和枚举是值类型
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 都是结构体
网友评论