Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Khoa Pham
Khoa Pham

Posted on

     

Instance property vs parameter in Swift

The other day I was refactor my code. I have

extension MainController: TabBarViewDelegate {  func buttonDidPress index: Int) {    let initialIndex = tabBarView.selectedIndex    let wholeAppContentView = updateWholeAppContentView()    view.addSubview(wholeAppContentView)  }}
Enter fullscreen modeExit fullscreen mode

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 section Rule 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.

extension MainController: TabBarViewDelegate {  func tabBarView(_ view: TabBarView, buttonDidPress index: Int) {    let initialIndex = tabBarView.selectedIndex    let wholeAppContentView = updateWholeAppContentView()    view.addSubview(wholeAppContentView) // This is the culprit ⚠️  }}
Enter fullscreen modeExit fullscreen mode

Even with just 1 line change in MainController.swift, the whole UI breaks, as all the views were added to the tab bar. Strange 😡 .

It didn’t take long until I remember that parameter takes precedence over instance property if they have same name. So in this case, the compiler, without warning, assume you're dealing with view from TabBarView ⚠️

That’s why you often use self to disambiguate.

struct User: Codable, Equatable {  let firstName: String  let lastName: String  init(firstName: String, lastName: String) {    self.firstName = firstName    self.lastName = lastName  }}
Enter fullscreen modeExit fullscreen mode

Back to our code. The workaround is to specify self to specify view of MainController

self.view.addSubview(wholeAppContentView)
Enter fullscreen modeExit fullscreen mode

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 😇

Original posthttps://medium.com/fantageek/instance-property-vs-parameter-in-swift-498c65252df8

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

My apps https://onmyway133.com/apps/
  • Joined

More fromKhoa Pham

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp