作者:幼俐佩其392 | 来源:互联网 | 2022-12-02 18:16
我注意到,即使没有明确要求(即在闭包之外),业内的一些人也会使用self关键字.
例:
import UIKit
import MapView
import CoreLocation
class viewController: UIViewController, MKMapViewDelegate, CLLocationDelegate {
let mapView = MKMapView()
let locatiOnManager= CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
self.mapView.showsUserLocation = true
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
}
运行时间方面是否有明显的好处?或者这纯粹是一种风格选择?
1> EmilioPelaez..:
有.
在你提供的例子中没有任何区别,它纯粹是一种风格选择.有些人可能会喜欢它,因为它明确告诉你你正在修改self
,我个人觉得它看起来更干净.
重要的是当你有一个同名的局部变量.假设你有一个var count: Int
有财产的班级.然后,在您的一个方法中,声明一个具有相同名称的新变量.
无论何时键入都将使用局部变量count
,因此如果要修改或读取对象的变量,则需要使用self
.
一些有用的例子:
guard let count = calculateCount() as? Int else { return }
self.count = count
init(count: Int) {
self.count = count
}
func updateCount(_ count: Int) {
self.count = count
}