Swift-protocols and Extensions

Source: Internet
Author: User



the code in the Swift programming language plus part Experiment


 
import UIKit

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
} class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() {
        simpleDescription += " Now 100% adjusted." }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure" mutating func adjust() {
        simpleDescription += " (adjusted)" }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription enum SimpleEnum: ExampleProtocol { case SIMPLE(String)
    var simpleDescription: String { get { switch self { case let .SIMPLE(str): return str
            }
        }
    }
    mutating func adjust() { switch self { case let .SIMPLE(str):
            self = .SIMPLE(str + " (adjusted)")
        }
    }
}
var c = SimpleEnum.SIMPLE("A simple enum")
c.simpleDescription
c.adjust()
c.simpleDescription

extension Int: ExampleProtocol {
    var simpleDescription: String { return "The number \(self)" }
    mutating func adjust() {
        self += 42 }
}
var d = 7 d.simpleDescription
d.adjust()

let protocolValue: ExampleProtocol = a
protocolValue.simpleDescription





Swift-protocols and Extensions


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.