Swift Basic: Only in Swift
Underscore: _
“ignore this”
Underscroe is used to define the parameter is not named.
In for-loop, “no index, just repeat.”
reference
Struct vs Class
: In Swift, struct and class have a lot in common.
init()- extension
- protocol
- subscript
- property & method
Then, when should I use struct or class?
I learned this from the example below.
- In my project Somking Area v1.0.0, there are 2 variables and 1 function related to loaction.
Addressstruct: has the information about locality and administrative area name.CLLocationCoordinate2D: store the latitude & longitude of the location.getCoordinateToAddress(coordinate: CLLocationCoordinate2D): get locality and adminitrative area name from the coordinate.
Therefore, I decided to combine the above three things as a single data structure. Location information is the
Modelin the project, so I tried to implement these as astruct.
struct Location {
internal init(coordinate: CLLocationCoordinate2D, administrativeArea: String, locality: String) {
self.coordinate = coordinate
self.administrativeArea = administrativeArea
self.locality = locality
}
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
self.administrativeArea = ""
self.locality = ""
exchangeCoordinateToAddress(coordinate: coordinate) {
(address) in
self.administrativeArea = address.administrativeArea
self.locality = address.locality
}
}
var coordinate: CLLocationCoordinate2D
var administrativeArea: String
var locality: String
func exchangeCoordinateToAddress(coordinate: CLLocationCoordinate2D, completion: @escaping ((Address)->())) {
......
}
}Above code did not work(Swift Error Note) because the struct is the value type, so exchangeCoordinateToAddress() method called in init() did not work.
So, class should be used in these cases,
- When you want to change the value. (call by reference)
- inheritance
- type casting
Most of other cases, there would be no problem to use struct.
Comments