An extension hides a property that I want to access. Workarounds?

六月ゝ 毕业季﹏ 提交于 2019-12-24 00:43:55

问题


I am using two pods: DropDown and SwiftyUtils.

DropDown adds in a UIView subclass called DropDown. The DropDown class defines its own width property. Instead of setting the frame, the client code has to set the width of the drop down menu using this property. It is defined like this:

public var width: CGFloat? {
    didSet { setNeedsUpdateConstraints() }
}

SwiftyUtils on the other hand, added an extension to all UIViews. In the extension, there is a width property as well. This width property is simply returning frame.width so that people can write less code. It is defined like this:

public var width: CGFloat {
    get { return frame.width }
    set { frame = frame.with(width: newValue) } // frame.with() is defined in SwiftyUtils as well
}

The problem comes when I try to set the DropDown's menu width using the width property defined in DropDwon. The compiler thinks that I mean the width property defined in the extension in the SwiftyUtils module.

How can I tell the compiler that what I mean is the width in DropDown, not the width in SwiftyUtils?


回答1:


I fixed this problem by a little trick.

The width in DropDown is of type CGFloat?, but the width in SwiftyUtils is of type CGFloat. This means that if I pass an optional CGFloat, the compiler will understand that I meant the width in DropDown.

So instead of doing this:

let menuWidth = <insert calculation here>
menu.width = menuWidth

I did this:

let menuWidth = <insert calculation here>
menu.width = menuWidth as CGFloat?


来源:https://stackoverflow.com/questions/42174748/an-extension-hides-a-property-that-i-want-to-access-workarounds

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