这里主要说一下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 UIKitclass 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,大家感兴趣的话可以认真看一下哦
总结以上是内存溢出为你收集整理的Swift接口和扩展全部内容,希望文章能够帮你解决Swift接口和扩展所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)