Skip to content

Instantly share code, notes, and snippets.

View LeeKahSeng's full-sized avatar

Lee Kah Seng LeeKahSeng

View GitHub Profile
protocol MyProtocol {
var myVar1: String { get set }
var myVar2: String { get }
}
struct MyStruct: MyProtocol {
var myVar1 = ""
var myVar2 = ""
}
var testStruct = MyStruct()
testStruct.myVar1 = "test var1"
testStruct.myVar2 = "test var2"
print(testStruct.myVar1) // "test var1"
print(testStruct.myVar2) // "test var2"
var testProtocol: MyProtocol = MyStruct()
testProtocol.myVar1 = "test var1" // No error
testProtocol.myVar2 = "test var2" // error: cannot assign to property: 'myVar2' is a get-only property
protocol Flyable {
/// Limit the speed of flyable
var speedLimit: Int { get set }
func fly()
}
extension Flyable {
func fly() {
class Bird: Flyable {
var speedLimit = 20
}
protocol Flyable {
// Make speedLimit only gettable
var speedLimit: Int { get }
func fly()
}
class Bird: Flyable {
// Make speedLimit private
private(set) var speedLimit = 20
protocol Flyable {
/// Limit the speed of flyable
var speedLimit: Int { get }
func fly()
}
extension Flyable {
func fly() {
protocol Animal {
associatedtype FoodType
func eat(food: FoodType)
}
protocol Animal {
var name: String { get }
func walk()
}
class Cow: Animal {
let name: String
protocol Animal {
var name: String { get }
func walk()
associatedtype FoodType
func eat(food: FoodType)
}
class Cow: Animal {