这里主要说一下swift中的接口,其中类、结构体和枚举都可以实现接口。下面通过代码来分别实现一下
//
// ViewController.swift
// swiftDemo
//
// Created by Jack on 16/4/6.
// Copyright © 2016年 Jack. All rights reserved.
//
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
//类、枚举和结构体都可以实现接口。
class SimpleClass: ExampleProtocol { //类实现接口
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
let a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
print(aDescription);
struct SimpleStructure: ExampleProtocol { //结构体实现接口
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
print(bDescription);
enum MyEnum: ExampleProtocol { //枚举实现接口
case Earth,Moon,Mars
var simpleDescription: String {
get {
switch self {
case .Earth:
return "earth"
case .Moon:
return "moon"
case .Mars:
return "mars"
}
}
}
mutating func adjust() {
switch self {
case .Earth:
self = .Moon
case .Moon:
self = .Mars
case .Mars:
self = .Earth
}
}
}
var myEnum = MyEnum.Earth
print(myEnum.simpleDescription)
myEnum.adjust()
print(myEnum.simpleDescription)
myEnum.adjust()
print(myEnum.simpleDescription)
myEnum.adjust()
print(myEnum.simpleDescription)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
其中,最后一个枚举实现接口是书中的一个练习题,好不容易从网上找到的一个demo,大家感兴趣的话可以认真看一下哦
原文链接:https://www.f2er.com/swift/324092.html