日常随笔第八弹-枚举/结构体/可选类型

2016-07-21  本文已影响12人  没有北方的南方

枚举

enum weekend {
    case mon
    case tue
    case wed
    case thu
    case fri
    case sat
    case sun
}

var day : weekend
day = .fri

if day == .fri{
    print("今天是星期五")
}
else {print("今天不是星期五")}

switch day {
case .sun :
    print("放假咯")
case .sat :
    print("放假咯")
case .fri :
    print("明天放假咯,有点小激动呢")
default :
    print("继续工作")
}

可选类型(!与?)

var i:Int?
i = 23
print(i)

i = nil//将i设为空
print(i!+23)

if let a = i {
    print(a, i)
}
else
{
    print("值为空")
}

func xx(b: Int?)->Int{
    guard let a = b else{
            print("空的")
        return 0
    }
    print(a)
    return a
}

var r = xx(23)
print(r)

var q = i ?? 1234//进行判断是否为空,不为空则取后面的值
print(q)

//Int?:必须使用!拆包取值
//Int!:自动拆包取值
var w:Int!
w = 345
print(w+34)

结构体

struct ss {
    var name : String?
    var number : Int?
    var age : UInt?
    func infoprint(){//结构体的方法,不能改变成员的值
        print(name, number, age)
    }
    static var i = 123 //静态成员,需要用类型名来调用
    init() {//定义构造函数,对结构体成员进行初始化赋值
        name = ""
        number = 0
        age = 0
    }
    init(name:String){
        self.name = "s"
    }
    init(number:Int){
        self.number = 23
    }
    
}

var ss1 = ss()
ss1.name = "hanghuo"
ss1.number = 01
ss1.age = 21

var ss2 = ss()
ss2.name = "yuyun"
ss2.number = 02
ss2.age = 22

print(ss1.name, ss2.age)

var ss3 = ss2
ss3.name = "fujin"
print(ss3.name, ss3.age, ss3.number)
上一篇下一篇

猜你喜欢

热点阅读