NSDictionaryOfVariableBindings swift equivalent?

前端 未结 7 1919
闹比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:25

    Based on https://stackoverflow.com/a/55086673/1058199 by cherpak-evgeny, this UIViewController extension assumes that the container is self, the current viewController instance.

    extension UIViewController {
    
        // Alex Zavatone 06/04/2019
        // Using reflection, get the string name of the UIView properties passed in
        // to create a dictionary of ["viewPropertyName": viewPropertyObject…] like
        // Objective-C's NSDictionaryForVariableBindings.
        func dictionaryOfBindings(_ arrayOfViews:[UIView?]) -> Dictionary {
            var bindings = Dictionary()
            let viewMirror = Mirror(reflecting: self)
            let _ = viewMirror.children.compactMap {
                guard let name = $0.label, let view = $0.value as? UIView else { return }
                guard arrayOfViews.contains(view) else { return }
                bindings[name] = view
            }
            return bindings
        }
    }
    

    Use it like so from within your viewController:

    let viewArray = [mySwitch, myField, mySpinner, aStepper, someView]
    let constraintsDictionary = dictionaryOfBindings(viewArray)
    

    Tested in Xcode 10.2.1 and Swift 4.2.

    Many thanks to Cherpak Evgeny for writing it in the first place.

提交回复
热议问题