Swift 協(xié)議在實(shí)際應(yīng)用中有很多用途,它們提供了一種靈活的方式來定義對(duì)象之間的共享行為。以下是一些 Swift 協(xié)議的常見實(shí)際應(yīng)用:
protocol Animal {
func speak() -> String
}
class Dog: Animal {
func speak() -> String {
return "Woof!"
}
}
class Cat: Animal {
func speak() -> String {
return "Meow!"
}
}
func makeAnimalSpeak(animal: Animal) {
print(animal.speak())
}
let dog = Dog()
let cat = Cat()
makeAnimalSpeak(animal: dog) // 輸出 "Woof!"
makeAnimalSpeak(animal: cat) // 輸出 "Meow!"
protocol Shape {
func area() -> Double
}
class Circle: Shape {
var radius: Double
init(radius: Double) {
self.radius = radius
}
func area() -> Double {
return .pi * radius * radius
}
}
class Rectangle: Shape {
var width: Double
var height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
func area() -> Double {
return width * height
}
}
func printShapeArea(shape: Shape) {
print("The area of the shape is \(shape.area())")
}
let circle = Circle(radius: 5)
let rectangle = Rectangle(width: 4, height: 6)
printShapeArea(shape: circle) // 輸出 "The area of the shape is 78.53981633974483"
printShapeArea(shape: rectangle) // 輸出 "The area of the shape is 24.0"
protocol Sortable {
static func < (lhs: Self, rhs: Self) -> Bool
}
extension Int: Sortable {}
extension Double: Sortable {}
func sort<T: Sortable>(_ array: inout [T]) {
array.sort()
}
var numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sort(&numbers)
print(numbers) // 輸出 "[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]"
protocol ButtonDelegate {
func buttonTapped()
}
class ViewController: UIViewController, ButtonDelegate {
@IBAction func buttonClicked(_ sender: UIButton) {
buttonTapped()
}
func buttonTapped() {
print("Button tapped!")
}
}
class AnotherViewController: UIViewController {
var delegate: ButtonDelegate?
@IBAction func anotherButtonClicked(_ sender: UIButton) {
delegate?.buttonTapped()
}
}
let viewController = ViewController()
let anotherViewController = AnotherViewController()
anotherViewController.delegate = viewController
anotherViewController.anotherButtonClicked(sender: UIButton()) // 輸出 "Button tapped!"
這些示例展示了 Swift 協(xié)議在實(shí)際應(yīng)用中的一些常見用途。通過使用協(xié)議,您可以編寫更靈活、可擴(kuò)展和可維護(hù)的代碼。