【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

你可能感兴趣的:(Swift,swift)