当前位置: 首页 > article >正文

【Swift】面向协议编程之HelloWorld

  • 定义一个协议(protocol),swift 中可以对protocol 进行扩展(extension)
  • 通过协议的扩展可以对函数有默认的实现
protocol Sleepable {
    func sleep()
}
protocol Eatable {
    func eat()
}
extension Eatable {
    func eat() {
        print("eat food")
    }
}
  • 在类(class)或结构体(struct)中实现protocol
//结构体实现协议
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")
    }
}
//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)扩展协议功能
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"
  • 枚举实现协议

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 方法
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.kler.cn/a/584116.html

相关文章:

  • 网络安全与七层架构
  • 【AIGC图生视频】蓝耘实践:通义万相2.1进阶玩法
  • 爬虫逆向:Unicorn 详细使用指南
  • 城市客运安全员适合哪几类人报考
  • 卷积神经网络(笔记03)
  • Android调试工具之ADB
  • WPF未来展望:紧跟技术发展趋势,探索新的可能性
  • Spring Boot 集成 Lua 脚本:实现高效业务逻辑处理
  • 抖音生活服务联动监管开展专项整治 济南66家违规餐饮商家下架
  • springboot websocket语音识别翻译
  • 代码随想录二刷|图论2
  • LVGL 中设置 UI 层局部透明,显示下方视频层
  • 微软 NativeAOT
  • 如何使用 ONLYOFFICE 宏对 PDF 表单中的特定字段执行计算
  • C语言为例谈数据依赖性
  • Vision Mamba论文精读笔记
  • VSCode 搭建C++编程环境 2025新版图文安装教程(100%搭建成功,VSCode安装+C++环境搭建+运行测试+背景图设置)
  • 各类神经网络学习:(二)RNN 循环神经网络(上集),模型类型和相关知识
  • 【原创】在宝塔面板中为反向代理添加Beare认证
  • Markdown:Mermaid 画图