NSDictionaryOfVariableBindings swift equivalent?

前端 未结 7 1922
闹比i
闹比i 2020-12-08 01:47

The Apple documentation shows an unsettling blank space under the \'Creating a Dictionary\' section of the UIKit reference here.

Has anyone found a replacement for

7条回答
  •  星月不相逢
    2020-12-08 02:26

    NSDictionaryOfVariableBindings is, as you say, a macro. There are no macros in Swift. So much for that.

    Nonetheless, you can easily write a Swift function to assign string names to your views in a dictionary, and then pass that dictionary into constraintsWithVisualFormat. The difference is that, unlike Objective-C, Swift can't see your names for those views; you will have to let it make up some new names.

    [To be clear, it isn't that your Objective-C code could see your variable names; it's that, at macro evaluation time, the preprocessor was operating on your source code as text and rewriting it — and so it could just use the text of your variable names both inside quotes (to make strings) and outside (to make values) to form a dictionary. But with Swift, there is no preprocessor.]

    So, here's what I do:

    func dictionaryOfNames(arr:UIView...) -> Dictionary {
        var d = Dictionary()
        for (ix,v) in arr.enumerate(){
            d["v\(ix+1)"] = v
        }
        return d
    }
    

    And you call it and use it like this:

        let d = dictionaryOfNames(myView, myOtherView, myFantasicView)
        myView.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "H:|[v2]|", options: nil, metrics: nil, views: d)
        )
    

    The catch is that it is up to you to realize that the name for myOtherView in your visual format string will be v2 (because it was second in the list passed in to dictionaryOfNames()). But I can live with that just to avoid the tedium of typing out the dictionary by hand every time.

    Of course, you could equally have written more or less this same function in Objective-C. It's just that you didn't bother because the macro already existed!

提交回复
热议问题