美文网首页
swift-structure、enumeration、clas

swift-structure、enumeration、clas

作者: sky_fighting | 来源:发表于2018-06-30 11:48 被阅读23次

swift的三种类型:结构体(structure)、枚举(enumeration)、类(class)
其中引用类型为class,值类型为structureenumeration

在swift中,structureenumeration与oc不同处在于其可以定义方法,包括实例方法和类方法
1、结构体
举个例子:

结构体Student
struct Student {
    // MARK: - 属性
    var name: String
    var age: Int
    var classNum: String
    // MARK: - 方法
    func descriptionStudent() {
        print("姓名:" + name + " 年龄:" + "\(age)" + " 班级号:" + classNum)
    }
}
调用
var student1 = Student(name: "andy", age: 15, classNum: "0501")
student1.descriptionStudent()
结果
姓名:andy 年龄:15 班级号:0501

如上述例子中,定义了descriptionStudent方法,不过呢,在该实例方法中是不能修改其变量的,比如:

修改属性报错.png
那为了要在实例方法中修改属性值,就要用到关键字 mutating
// MARK: - 修改属性例1
mutating func modifyName(name: String){
    self.name = name
}
调用
// MARK: - 结构体修改属性
student1.modifyName(name: "王五")
print("结构体修改属性name:" + student1.name)
输出
结构体修改属性name:王五

结构体扩展

extension Student{
    func classDescription() {
        print("结构体扩展" + self.classNum)
    }
}
调用
student1.classDescription()
输出
结构体扩展0501

2、枚举

// MARK: - 指南针方向枚举
enum CompassPoint {
    case North(param: String)  //北
    case Sourth //南
    case West  //西
    case East  //东
    // MARK: - 枚举中可以定义方法
    func showPoint() {
        print(self)
    }
}
调用
let compassPoint1 = CompassPoint.North(param: "error")
let compassPoint2 : CompassPoint = .West
compassPoint1.showPoint()
compassPoint2.showPoint()
结果
North("error")
West

枚举同样也可以实现修改属性、扩展方法等,写法同结构体
3、类

class Person {
    var name: String
    var sex: String
    init(name: String, sex: String){
        self.name = name
        self.sex = sex
    }
    func description() -> String{
        return "\(name) \(sex)"
}

类和结构体的相同点:
a、属性
b、方法
c、下标操作
d、构造器
e、扩展
f、协议
类和结构体的不同点:
类具有:继承、析构、类型转换、引用计数

类和结构体在内存中的实现机制的不同:
类存储在堆(heap)中,结构体存储在栈(stack)中
类是引用类型,而结构体是值类型

参考自https://blog.csdn.net/Yarn_/article/details/75224541

相关文章

  • swift-structure、enumeration、clas

    swift的三种类型:结构体(structure)、枚举(enumeration)、类(class)其中引用类型为...

  • Enumerations

    Enumeration Syntax The name of enumeration starts with a ...

  • Enumeration与Iterator介绍

    Enumeration Enumeration简介 Enumeration(列举),本身是一个接口,不是一个类。E...

  • Swift Enumeration(斯威夫特枚举)

    Swift Enumeration(斯威夫特枚举) 目录:1、Enumeration Syntax(枚举语法)2、...

  • Enumeration

    区别于C,swift中的枚举更加灵活。不需要为每个枚举设定值,如果为枚举设定值得话(raw),可以是字符串、字符、...

  • Enumeration

    1.背景介绍 枚举是一个比较重要的知识点,在之前做任务的时候简单的接触了一下,所以这次给大家介绍一下,抛砖引玉。 ...

  • java复习

    Iterator和Enumeration的区别 我们通常用Iterator(迭代器)或者Enumeration(枚...

  • Enumeration接口

    在学习properties类的过程使用到Enumeration接口,因此学习记录下。 Enumeration接口中...

  • Enumeration 接口浅析

    注:基于 jdk 1.8 版本。 一、Enumeration 是什么? Enumeration 不是一个数据结构,...

  • Enumeration接口,StringTokenizer,Ha

    Enumeration接口 该接口较为古老,但在维护以前的程序时就会频繁遇到。枚举Enumeration接口,作用...

网友评论

      本文标题:swift-structure、enumeration、clas

      本文链接:https://www.haomeiwen.com/subject/guhtuftx.html