Original posthttps://github.com/onmyway133/blog/issues/72
The other day I was refactor my code. I have
extensionMainController:TabBarViewDelegate{funcbuttonDidPressindex:Int){letinitialIndex=tabBarView.selectedIndexletwholeAppContentView=updateWholeAppContentView()view.addSubview(wholeAppContentView)}}
The delegate method does not look right, as it's hard to tell between required delegate method, or just instance method. Also it lacks a subject. I like this postAPI Design, you can read sectionRule 19: Always say who’s talking
This is a simple rule, and an equally simple mistake to make. In your delegate methods, always pass the sender as a parameter. Always. Even for singletons. Even for things you cannot conceive would ever be used more than once simultaneously. No exceptions.
So I refactor the delegate, and conform to it.
extensionMainController:TabBarViewDelegate{functabBarView(_view:TabBarView,buttonDidPressindex:Int){letinitialIndex=tabBarView.selectedIndexletwholeAppContentView=updateWholeAppContentView()view.addSubview(wholeAppContentView)// This is the culprit âš ï¸}}
Even with just 1 line change inMainController.swift
, the whole UI breaks, as all the views were added to the tab bar. Strange 😡 .
It didn't take long until I remember thatparameter
takes precedence overinstance property
if they have same name. So in this case, the compiler, without warning, assume you're dealing withview
fromTabBarView
âš ï¸
That's why you often useself
to disambiguate.
structUser:Codable,Equatable{letfirstName:StringletlastName:Stringinit(firstName:String,lastName:String){self.firstName=firstNameself.lastName=lastName}}
Back to our code. The workaround is to specifyself
to specifyview
ofMainController
self.view.addSubview(wholeAppContentView)
Well, you may say, who should add view again in case of tab bar changes 😬 This is a bad example, but the lesson is learned 😇
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse