swift编程开发首页投稿(暂停使用,暂停投稿)iOS Developer

Swift超基础语法(枚举与结构体篇)

2016-07-30  本文已影响108人  S_Lyu

枚举

enum SomeEnumeration {
        // enumeration definition goes here
}
例:枚举类型的基本定义方法和使用
        enum season {
            case spring
            case summer
            case automn
            case winter
        }
        enum season {
            case spring, summer,automn,winter
        }
        let se = season.automn //枚举名.枚举值
        let se : season = .automn  //定义变量为某个枚举类型的值,使用时直接.枚举值
        enum season1 : String {
            case spring = "lyu"
            case summer = "sim"
            case automn 
            case winter 
        }
        enum season2 : Int {
            case spring = 1, summer , automn, winter
        }  //系统会自动将summer赋值为2以此类推
        let se1 = season1.init(rawValue: "sim")
        let se2 = season2.init(rawValue: 2)

结构体

struct 结构体名称{
属性和方法  //注意Swift中的结构体可以定义方法哦
}
例:定义结构体表示一个点
struct Location {
var x : Double
var y : Double
}
例:使用上例的结构体
let center =Location(x : 100 , y : 100)
        struct myPoint {
            var x : CGFloat
            var y : CGFloat
            init (x : CGFloat , y : CGFloat){  //扩充构造方法
                self.x = x
                self.y = y
            }
            init (name : String) {  //扩充构造方法
                self.x = 10
                self.y = CGFloat(name.characters.count)
            }
        }
        let testCenter = myPoint(x: 100 , y: 100)  // (100.0 , 100.0) 
        let testC2 = myPoint(name : "lyu")  // (10.0 3.0)

}

        struct myPoint {
            var x : CGFloat
            var y : CGFloat
            init (x : CGFloat , y : CGFloat){
                self.x = x
                self.y = y
            }
            init (name : String) {
                self.x = 10
                self.y = CGFloat(name.characters.count)
            }
            mutating func printSelf(){  //为结构体扩充函数
                print(self)
            }
        }
        var testCenter = myPoint(x: 100 , y: 100)  //使用扩充的构造方法
        testCenter.printSelf()  //调用扩充的函数
例:给系统的结构体扩充方法
import UIKit
extension CGPoint {
    mutating func printSelf(){
        print(self)
    }
}
//调用方法
var center = CGPoint(x: 100, y: 100)
center.printSelf()  //打印自身
上一篇 下一篇

猜你喜欢

热点阅读