Why isn't viewWithTag and some other methods renamed in Swift 3?

雨燕双飞 提交于 2020-01-07 02:37:10

问题


In Swift 3, a lot of the methods got renamed. According to one of the sessions at WWDC, the prepositions in method names are moved to the parameter name:

UIView.animateWithDuration(1)
 -> UIView.animate(withDuration: 1)

UIStoryboard.instantiateViewControllerWithIdentifier("some stuff")
 -> UIStoryboard.instantiateViewController(withIdentifier: "some stuff")

So I thought viewWithTag(1) will be renamed to view(withTag: 1), but it isn't!

There is even mentioned in the API guidelines:

Especially when a parameter type is NSObject, Any, AnyObject, or a fundamental type such Int or String, type information and context at the point of use may not fully convey intent. In this example, the declaration may be clear, but the use site is vague.

func add(_ observer: NSObject, for keyPath: String)
grid.add(self, for: graphics) // vague

To restore clarity, precede each weakly typed parameter with a noun describing its role:

func addObserver(_ observer: NSObject, forKeyPath path: String)
grid.addObserver(self, forKeyPath: graphics) // clear

I also found that SKNode.addChild is not renamed as well!

Question:

Why are these methods not renamed? They forgot about them? Or are there exception cases to the API guidelines? If yes, what are them?


回答1:


I am looking into the algorithm described in Swift Evolution 0005.

  1. viewWithTag

The first step of name pruning is:

  1. Prune the result type from the head of type-preserving transforms. Specifically, when

    • the receiver type is the same as the result type
    • and the type name is matched at the head of the first selector piece
    • and the match is followed by a preposition

the view part is actually the first to be removed.

The forTag is removed too in step 3, therefore the result is an empty selector.

That collides with

Pruning Restrictions ...

  • Never make a selector piece entirely empty.

Therefore no pruning is performed.

  1. addChild

addChild, addSubview, addGestureRecognizer follow all the same pattern, there is actually an example in the spec:

  • Never prune a suffix from the base name of a method that matches a property of the enclosing class:

This heuristic has the effect of preventing us from producing too-generic names for methods that conceptually modify a property of the class.

... If we were to drop GestureRecognizer, leaving just add, we end up with a method that conceptually modifies the gestureRecognizers property but uses an overly generic name to do so:

In general, they cannot forget about some methods because the renaming (importing) is automatical.



来源:https://stackoverflow.com/questions/40114956/why-isnt-viewwithtag-and-some-other-methods-renamed-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!