//: Playground - noun: a place where people can play
import UIKit
/*
* 本节主要内容:
* 1.添加可失败的构造方法
*/
struct LocationNew {
var latitude: Double = 0.0
var longitude: Double = 0.0
// 添加可选型属性
var placeName: String? // nil
// 假定参数格式: "39.123,116.456"
// 错误参数格式: "39.123*116.456"
// init?(coordinateString: String) {
// // 获取子字符串
// if let commaRange = coordinateString.range(of: ",") {
// // 1.获取逗号所在的index
// let commaIndex = coordinateString.index(commaRange.lowerBound, offsetBy: 0)
// // 2.subString to获取纬度
// if let firstElement = Double(coordinateString.substring(to: commaIndex)) {
// // 3.subString from获取经度
// if let secondElement = Double(coordinateString.substring(from: coordinateString.index(commaIndex, offsetBy: 1))) {
// // 经纬度都可以获取
// latitude = firstElement
// longitude = secondElement
// } else {
// // 获取经度失败
// return nil
// }
// } else {
// // 获取纬度失败
// return nil
// }
// } else {
// // 无法获取逗号的index
// return nil
// }
// }
// guard语句来优化上面的代码
init?(coordinateString: String) {
// 获取子字符串
guard let commaRange = coordinateString.range(of: ",") else {
return nil
}
// 1.获取逗号所在的index
let commaIndex = coordinateString.index(commaRange.lowerBound, offsetBy: 0)
// 2.subString to获取纬度
guard let firstElement = Double(coordinateString.substring(to: commaIndex)) else {
return nil
}
// 3.subString from获取经度
guard let secondElement = Double(coordinateString.substring(from: coordinateString.index(commaIndex, offsetBy: 1))) else {
return nil
}
// 经纬度都可以获取
latitude = firstElement
longitude = secondElement
}
init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
}
init() {
latitude = 0.0
longitude = 0.0
}
// 再加一个构造方法: 包含所有属性(推荐)
init(latitude: Double, longitude: Double, placeName: String) {
self.latitude = latitude
self.longitude = longitude
self.placeName = placeName
}
// 自定义方法
func isNorth() -> Bool {
return latitude > 0.0
}
func isSouth() -> Bool {
return !isNorth()
}
// 模拟计算两个点的距离
func distanceTo(location: LocationNew) -> Double {
return sqrt(pow((self.latitude - location.latitude), 2) + pow((self.longitude - location.longitude), 2))
}
}
// 实例化, 调用可失败的构造方法
// init?本质就是返回LocationNew?
// location和locationNew都是LocationNew?类型
var location = LocationNew(coordinateString: "39.34,122.3535")
var locationNew = LocationNew(coordinateString: "23.34,122.3535")
locationNew?.isNorth()
locationNew?.distanceTo(location: location!)
Swift 系统学习 20 结构体 添加可失败的构造方法
最新推荐文章于 2024-12-10 14:43:21 发布