swift学习之类和结构体(class struct、enum)

class struct enum
enum
枚举是为一组有限种可能性的相关值提供的通用类型,关键词enum来定义枚举,在一对大括号内定义具体内容包括使用case关键字列举成员
枚举中有两个概念:原始值(raw value)、关联值(associated value),
1.枚举的原始值
枚举成员可以用相同类型的默认值预先填充,这样的值就是原始值(raw value),Int修饰的是FruitType成员原始值的类型而不是FruitType的类型

enum FruitType: Int{
    case apple = 10
    case orange = 11
    case banana = 15
}

可以使用枚举成员的rawValue属性来访问成员的原始值,或者是使用原始值初始化器来尝试创建一个枚举实例
2.枚举的关联值(associated value)
关联值是为枚举的成员们绑定了一组类型,不同的成员可以是不同的类型(提供关联值时用的是括号)

enum FruitType{
    case apple (String)
    case orange (Int,String)
    case banana (Int,String)
}
var apple = FruitType.apple("app")
var orange = FruitType.orange(5, "org")
var banana = FruitType.banana(10, "ban")
switch banana {
case .apple(let value):
    print(value)
case .banana(let num,let name):
    print("\(name) has \(num)")
default:
    print("default")
}
let apple = FruitType. apple.rawValue
print(apple)//10
let orange = FruitType.init(rawValue: 11)
print(orange!)//orange
let ban = FruitType.init(rawValue: 16)
if ban == nil{
    print("nil")
}

枚举、结构体、类的共同点:
1,定义属性和方法;
2,下标语法访问值;
3,初始化器;
4,支持扩展增加功能;
5,可以遵循协议;
二.不同点
类具有结构体不具有的功能如下:
类特有的功能:
1,继承;
2,允许类型转换;
3,析构方法释放资源;
4,引用计数;
类和结构体区别
1.定义结构体类型时其成员可以没有初始值。定义一个类没有初始值,编译器是会报错的,他会提醒这个类没有被初始化。
2.定义结构体类型时其成员可以没有初始值,但是创建结构体实例时该实例的成员必须有初值。
3.在结构体内部方法中如果修改了结构体的成员,那么该方法之前应该加入:mutating关键字,结构传递 是作为值传递 ,所以要inout处理
4.class是引用类型 strcut 是值类型

struct Student {
    var chinese: Int = 50
    var math: Int = 50
    var english: Int = 50
   //修改数学成绩
    mutating func changeMath(num: Int) {
        self.math += num
    }
  }
 var student = Student(chinese: 20, math: 30, english: 40)
//更改结构体属性值
//方法1
//更改分数中语文学科的成绩
func changeChinese(num: Int, student: inout Student){
    student.chinese += num
}
changeChinese(num: 20, student: &student)
print(student.chinese,student.math)
//方法2
student.changeMath(num: 10)

class是引用类型 strcut 是值类型

struct SRect {
    var width = 100
    var height = 100
}
class CRect {
    var width = 100
    var height = 100
}

var sRect = SRect(width: 150, height: 150)
print("struct===\(sRect.width)==\(sRect.height)")
var cRect = CRect()
print("class===\(cRect.width)==\(cRect.height)")

var newSrect = sRect
print(newSrect.width,newSrect.height)
newSrect.width = 200
newSrect.height = 200

print("struct是值类型")
print("newSrect===\(newSrect.width)==\(newSrect.height)")
print("srect===\(sRect.width)==\(sRect.height)")

var newCRect = cRect
newCRect.width = 300
newCRect.height = 300
print("class是引用类型")
print("newCRect===\(newCRect.width)==\(newCRect.height)")
print("crect===\(cRect.width)==\(cRect.height)")

输出结果:

struct===150==150
class===100==100
150 150
struct是值类型
newSrect===200==200
srect===150==150
class是引用类型
newCRect===300==300
crect===300==300

你可能感兴趣的:(swift学习之类和结构体(class struct、enum))