2016. 8. 7. 13:24ㆍSwift
// Protocols and Extensions
protocol ExampleProtocol {
var simpleDescription: String {
get
}
mutating func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69015
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDiscription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += "(adusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
extension Double: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42.0
}
mutating func absoluteValue() {
self = abs(-21.0)
}
}
var c: Double = 10.0
c.absoluteValue()
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
extension String {
var length: Int {
return self.characters.count
}
func reverse() -> String {
return self.characters.reverse().map {
String($0)
}.joinWithSeparator("")
}
}
let str = "안녕하세요"
str.length // 5
str.reverse() // 요세하녕안
출처 : The Swift Programming Language(iBook)
https://devxoul.gitbooks.io/ios-with-swift-in-40-hour/content/Chapter-3/extensions.html