importCocoa// ## protocol// {get set} -> no comman in between// {get} or {get set}, not possible for just {set}protocolVehicle{varname:String{get}varcurrentPassengers:Int{getset}funcestimateTime(fordistance:Int)->Intfunctravel(distance:Int)}structRocket:Vehicle{letname="rocket"varcurrentPassengers=0funcestimateTime(fordistance:Int)->Int{returndistance/100}functravel(distance:Int){print("\(name) traveled \(distance) already")}}varr=Rocket()r.travel(distance:12)// opaque return type/*
they let us hide information in our code, but not from the Swift compiler.
This means we reserve the right to make our code flexible
internally so that we can return different things in the future,
but Swift always understands the actual data type being returned
and will check it appropriately.
*/funcgetRandomNumber()->someEquatable{Int.random(in:1...6)}/*
when you see some View in your SwiftUI code, it’s effectively us telling
Swift “this is going to send back some kind of view to lay out, but I don’t
want to write out the exact thing – you figure it out for yourself.”
*/// ## Extentions/*
Extensions let us add functionality to any type, whether we created it or
someone else created it – even one of Apple’s own types.
*/extensionString{functrimmed()->String{self.trimmingCharacters(in:.whitespacesAndNewlines)}}leta=" hello world "print(a.trimmed())/*
If want to change the string itself, use:
mutating func trim() {
self = self.trimmed()
}
*/// ## can add computed property extension to a type/*
var lines: [String] {
self.components(separatedBy: .newlines)
}
*/// ## put custom init in extension/*
if we implement a custom initializer inside an extension, then Swift won’t
disable the automatic memberwise initializer.
extension Book {
init(title: String, pageCount: Int) {
self.title = title
self.pageCount = pageCount
self.readingHours = pageCount / 50
}
}
*/// ## protocol extensionsextensionCollection{varisNotEmpty:Bool{isEmpty==false}}// use extension to implement a default method in protocolprotocolPerson{varname:String{get}funcsayHello()}extensionPerson{funcsayHello(){print("Hi, I'm \(name)")}}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)