swift的基本使用(5)类和枚举

//: Playground - noun: a place where people can play

import UIKit

//枚举
//enum 枚举名: 类型{
// case 分支名1 = 赋值1
// case 分支名2 = 赋值2
//}

enum PersonIndentity : String{
case Teacher = “Teacher_id”
case Student = “Student_id”
}

//类
class Person {
var indentity : PersonIndentity?
var name: String?
var sex: String

//类的构造器
init (name:String, sex:String, idd:PersonIndentity){
    self.name = name
    self.sex = sex
    self.indentity = idd
}


//方法
func hello() {
    println("hello \(self.name)")
}

class func hello2() {
    println("hello word")
}

//类型属性 只能是计算属性
class var home: String {

    get{

        return "地球"

    }
}

}
//使用枚举时, 枚举名.类型
//也可以进行简化 .类型
//var student = Person(name: “dj”, sex: “f”, idd: PersonIndentity.Student)
var student = Person(name: “dj”, sex: “f”, idd: .Student)
//枚举值的获得
//代表枚举分支的行
student.indentity?.hashValue
//代表枚举分支具体的值
student.indentity?.rawValue
student.hello()
Person.hello2()
Person.home

//继承
class Student: Person {
var classNumber: Int
init(name: String, sex: String, idd: PersonIndentity, classNumber: Int) {
//子类的特有属性要在super.init前面进行赋值
self.classNumber = classNumber
super.init(name: name, sex: sex, idd: idd)

}

func helloStudent () {
    println("子类方法")
}

//重写父类方法 需要使用override关键字
override func hello() {
    println("重写父类方法")
}

override class func hello2() {
    println("重写父类类型方法")
}

}

//协议
protocol OneProtocol {
func typeFunc()
static func typeFunc2()
// class func typeFunc3()

mutating func typeFunc4()

}

//继承协议,实现方法的时候,要根据结构体或类本身的语法做出调整,不能仅依靠提示
struct StructNew : OneProtocol {
func typeFunc() {

}
static func typeFunc2() {

}
func typeFunc4() {

}

}

class ClassNew: OneProtocol{
func typeFunc() {

}
class func typeFunc2() {

}
func typeFunc4() {

}

}

//若想实现方法可选实现,需要使用optional关键字,optional关键字实现条件是必须是@objc的协议, eg:@objc protocol
//但此时 协议不能被结构体继承
@objc protocol TwoProtocol{
optional func typeFunc3()
}

//struct StrucNew2: TwoProtocol {
//
//}

//如果同时继承协议和父类,父类需要写在前面
class ClassNew2:ClassNew, TwoProtocol{

}

//延展
var studentEX = “stu”
extension Person {
func hello5(){

}

//延展不能添加存储属性,只能添加计算属性
//var stu2: String = "jhhkk"
var stu2 :String {
    get{
        return studentEX
    }
    set{
        studentEX = newValue
    }
}

//convenience 扩展类的构造器的时候,涂药添加关键字
convenience init(name:String, sex:String, idd:PersonIndentity, stu:String) {
    self.init(name:name, sex: sex, idd: idd)
    self.stu2 = stu

}

}

var person = Person(name: “hj”, sex: “f”, idd: PersonIndentity.Student, stu: “djj”)
person.stu2 = “ggg”
person.stu2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值