zoukankan      html  css  js  c++  java
  • iOS二次发育(swift)结构体

    struct Location{
        var latitude: Double = 0
        var longitude: Double = 0
        //使用Failable-Initializer
        init?(coordinateString: String) {
            if let commaIndex = coordinateString.range(of: ","){
                if let firstElement = Double(coordinateString.substring(to: commaIndex.lowerBound)){
                    if let secondElement = Double(coordinateString.substring(from: commaIndex.upperBound)){
                        self.latitude = firstElement
                        self.longitude = secondElement
                    }else{
                        return nil
                    }
                }else{
                    return nil
                }
            }else{
                return nil
            }
        }
        init(latitude: Double, longitude: Double) {
            self.latitude = latitude
            self.longitude = longitude
        }
        
        init?(coordinateString2: String) {
            guard let commaIndex = coordinateString2.range(of: ",") else {
                return nil
            }
            guard let firstElement = Double(coordinateString2.substring(to: commaIndex.lowerBound)) else {
                return nil
            }
            guard let secondElement = Double(coordinateString2.substring(from: commaIndex.upperBound)) else {
                return nil
            }
            self.latitude = firstElement
            self.longitude = secondElement
        }
        
    }
    
    let appleHeadQuarterLocation = Location(coordinateString: "12,33")
    
    let appleHeadQuarterLocation2 = Location(latitude: 44, longitude: 55)
    
    let appleHeadQuarterLocation3 = Location(coordinateString2: "12?33")

     结构体函数自己修改自己需要加mutating关键字

    struct Location{
        var x = 0
        var y = 0
        mutating func goEast() {
            self.x += 1
        }
    }

    如果结构体对所有存储型属性提供了默认值且自身没有提供定制的构造器,它们能自动获得一个逐一成员构造器。

    struct Rectangle {
        //var length = 100.0, breadth = 200.0
        var length: Double, breadth: Double
        
    }
    //let area = Rectangle(length: 1.1, breadth: 2.2)
    
    let area = Rectangle(length: 3.3, breadth: 4.4)
  • 相关阅读:
    Docsify 如何在一个 MD 文件中嵌入另外一个文件
    集合与条件、循环语句
    字典(当索引不好用时)
    序列(列表、元组、字符串)
    变量、数据类型和运算符
    Python基础知识
    计算机基础知识
    Windows环境下Python2和Python3的安装
    操作系统基础
    计算机硬件基础知识
  • 原文地址:https://www.cnblogs.com/liuguan/p/7510567.html
Copyright © 2011-2022 走看看