接口和扩展

前端之家收集整理的这篇文章主要介绍了接口和扩展前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

//: Playground - noun: a place where people can play


import UIKit


//使用 protocol 来声明一个接口。

protocol ExampleProtocol {

var simpleDescription: String { get }

mutating func adjust()

}

//类、枚举和结构体都可以实现接口。

class SimpleClass: ExampleProtocol {

String = "A very simple class."

var anotherProperty: Int = 120

func adjust() {

@H_404_71@ simpleDescription@H_404_71@ += " Now 100% adjust."

}

func add() {

@H_404_71@ simpleDescription@H_404_71@ += " Now 50% add."

}

}

var@H_404_71@ a = SimpleClass@H_404_71@()

a@H_404_71@.adjust@H_404_71@()

let@H_404_71@ aDescription = a@H_404_71@.simpleDescription


struct SimpleStructure: ExampleProtocol {

String = "A aimple structure"

func adjust() {

@H_404_71@ simpleDescription@H_404_71@ += " (adjusted)"

}

}

var@H_404_71@ b = SimpleStructure@H_404_71@()

b@H_404_71@.adjust@H_404_71@()

let@H_404_71@ bDescription = b@H_404_71@.simpleDescription


enum SimpleEnum: ExampleProtocol {

case First(String),Second(String),Third(String)

String {

get{

switch self {

case let .First(text):

return text

let .Second(text):

let .Third(text):

default:

return "get error"

}

}

set {

self = .First(newValue)

self = .Second(newValue)

self = .Third(newValue)

}

}

}

func adjust() {

self {

let .First(text):

self = .First(text + " (first case adjust)")

let .Second(text):

self = .Second(text + " (Second case adjust)")

let .Third(text):

self = .Third(text + " (Third case adjust)")

}

}

}

var@H_404_71@ c = SimpleEnum@H_404_71@.First@H_404_71@("FirstVal"@H_404_71@)

c@H_404_71@.simpleDescription

c@H_404_71@.adjust@H_404_71@()

c@H_404_71@.simpleDescription

var@H_404_71@ d = SimpleEnum@H_404_71@.Second@H_404_71@("Hello"@H_404_71@)

var@H_404_71@ text = d@H_404_71@.simpleDescription

d@H_404_71@.simpleDescription@H_404_71@ = "Word"

text@H_404_71@ = d@H_404_71@.simpleDescription

d@H_404_71@.adjust@H_404_71@()

text@H_404_71@ = d@H_404_71@.simpleDescription

//注意声明 SimpleStructure 时候 mutating 关键字用来标记一个会修改结构体的方法SimpleClass 的声明不需要标记 任何方法因为类中的方法经常会修改类。


//使用 extension 来为现有的类型添加功能,比如添加一个计算属性方法。你可以使用扩展来给任意类型添加协议,甚至是你从外部库或者框架中导入的类型。

extension Int: ExampleProtocol {

String {

@H_404_71@ return@H_404_71@ "The number @H_404_71@\(self)"

}

self += 42

}

}

//你可以像使用其他命名类型一样使用接口名——例如,创建一个有不同类型但是都实现一个接口的对象集合。当你处理 类型是接口的值时,接口外定义的方法不可用。

let protocolValue: ExampleProtocol = a

protocolValue@H_404_71@.simpleDescription

//即使 protocolValue 变量运用时的类型是 simpleClass,编译器会把它的类型当做 ExampleProtocol。这表示你不能调用类在它实现的接口之外实现的方法或者属性

猜你在找的Swift相关文章