【Swift】面向协议编程之HelloWorld

news/2025/3/18 11:20:58
  • 定义一个协议(protocol),swift 中可以对protocol 进行扩展(extension)
  • 通过协议的扩展可以对函数有默认的实现
swift">protocol Sleepable {
    func sleep()
}
protocol Eatable {
    func eat()
}
extension Eatable {
    func eat() {
        print("eat food")
    }
}
  • 在类(class)或结构体(struct)中实现protocol
swift">//结构体实现协议
struct Cat: Eatable, Sleepable {
    func sleep() {
        print("cat sleep")
    }
}

class Animal {
    func say() {
        print("say hello")
    }
}

//类,继承和实现协议
class Dog: Animal, Eatable, Sleepable {
    func eat() {
        print("Dog eat")
    }

    func sleep() {
        print("Dog sleep")
    }
}
swift">//Cat为结构体
let cat = Cat()
cat.eat()
cat.sleep()

//Dog为class,继承了Animal的say方法,也获得了protocol的默认实现eat方法
let dog = Dog()
dog.eat()
dog.sleep()
dog.say()

//输出结果:
//eat food
//cat sleep
//eat food
//Dog sleep
//say hello
  • 为现有类型(Int ,String)扩展协议功能
swift">protocol Describable {
    func describe() -> String
}
extension Describable {
    func describe() -> String {
        return "This is the number \(self)"
    }
}

//Int使用默认的协议实现
extension Int: Describable {
    
}
extension String: Describable {
    func describe() -> String {
        return "This is the string \"\(self)\""
    }
}

let number: Describable = 42
print(number.describe()) // 输出:This is the number 42

let text: Describable = "Hello"
print(text.describe()) // 输出:This is the string "Hello"
  • 枚举实现协议
swift">
enum Pen:Printable{
    case normal
    
}
enum Book: Printable {
    case fiction, nonFiction, biography

    func printDetails() -> String {
        switch self {
        case .fiction:
            return "Fiction Book"
        case .nonFiction:
            return "Non-Fiction Book"
        case .biography:
            return "Biography Book"
        }
    }
}

 let pen = Pen.normal
 print(pen.printDetails())//This is a printable item.

 let book = Book.fiction
 print(book.printDetails()) // 输出:Fiction Book
  • 为所有遵循 RawRepresentable 协议的枚举类型提供一个通用的 printRawValue 方法
swift">protocol RawRepresentablePrintable: RawRepresentable {
    func printRawValue()
}

extension RawRepresentablePrintable {
    func printRawValue() {
        print("Raw value: \(self.rawValue)")
    }
}

enum Direction: Int, RawRepresentablePrintable {
    case north = 1
    case south = 2
    case east = 3
    case west = 4
}

let direction = Direction.north
direction.printRawValue() // 输出:Raw value: 1

http://www.niftyadmin.cn/n/5891060.html

相关文章

(每日一题) 力扣 179 最大数

文章目录 🎯 LeetCode 179 最大数:最优解法详解(C实现)📋 问题描述💡 核心思路🚀 完整代码实现🔍 分步解析1. 全零检测2. 字符串转换3. 自定义排序规则4. 拼接结果5. 处理前导零 &am…

Centos离线安装perl

文章目录 Centos离线安装perl1. perl是什么?2. Centos下载地址?3. perl的安装4. 安装结果验证 Centos离线安装perl 1. perl是什么? Perl 是一种 高级脚本语言,诞生于 1987 年,以强大的 文本处理能力 和灵活性著称&…

TDengine SQL 函数

单行函数 数学函数 ABSACOSASINATANCEILCOSDEGREESEXPFLOORGREATESTLEASTLNLOGMODPIPOWRADIANSRANDROUNDSIGNSINSQRTTANTRUNCATE 字符串函数 ASCIICHARCHAR_LENGTHCONCATCONCAT_WSLENGTHLOWERLTRIMPOSITIONREPEATREPLACERTRIMSUBSTRING/SUBSTRSUBSTRING_INDEXTRIMUPPER 转换函数…

计算机视觉|具身智能技术详解:视觉-动作联合建模的原理与实践

一、具身智能与视觉-动作联合建模简介 具身智能(Embodied Intelligence) 是人工智能领域的关键研究方向,强调智能体通过物理实体与环境交互实现认知和智能行为。与传统人工智能基于静态数据和符号推理不同,具身智能依赖动态感知与…

【3DGS】SuperSplat本地运行+修改监听端口+导入ply模型+修剪模型+在线渲染3DGS网站推荐

SuperSplat官网代码:https://github.com/playcanvas/supersplat 本地安装和运行 Clone the repository: git clone https://github.com/playcanvas/supersplat.git cd supersplat Install dependencies: npm install Build SuperSplat and start a local web ser…

聊一下CSS层叠

层叠,即页面各个元素在Z轴方向上的先后顺序,谁压着谁,谁覆盖着谁。其中z轴定义如下,也就是垂直于显示器的方向, css中,有一套自己的层叠计算规则,其中主要包含以下几个概念: 层叠上…

(vue)elementUi中el-upload上传附件之后 点击附件可下载

(vue)elementUi中el-upload上传附件之后 点击附件可下载 handlePreview(file) {console.log(file)const fileUrl https://.../zzy/ file.urlconst a document.createElement(a)a.href fileUrla.download file.namea.style.display none// a.setAttribute(download, file.…

H.264码率结构概念(I帧,帧,B帧)

I帧 I帧,帧内图像,在编码时候,采用帧内压缩编码,不参考其他帧图像,I帧可以作为其他帧的参考帧,一般视频序列中第一帧是I帧(也叫关键帧IDR). 帧内压缩编码的压缩比不会很大,但压缩得到图像质量较好.P帧 P帧,预测图像,通常采用帧间和帧内混合编码方式,需要参考前一帧的I图像或者…