Why does Apple choose to use nested struct types to replace 'String' type parameter?

144 views Asked by At

For example:

Before new version of Swift,I could write like this:

NSNib(nibNamed: "TagCellView", bundle: nil)

Now Apple is choosing to define a lots of nested struct types,like NSNib.Name,and now I have to write like this:

NSNib(nibNamed: NSNib.Name("TagCellView"), bundle: nil)

IMHO I think the old version is much cleaner, what's the reason behind Apple's choice?

1

There are 1 answers

2
rmaddy On BEST ANSWER

The point is to avoid scattering strings throughout your code. What you should do is define your constant for a given nib just once in your code. Then anywhere you need to use that nib name, you reference that one constant instead of retyping (possibly incorrectly) the hardcoded string.

You can define something like:

public struct MyNibs {
    public static let TagCellView = NSNib.Name("TagCellView")
}

And then use it as:

let nib = NSNib(nibNamed: MyNibs.TagCellView, bundle: nil)

Even cleaner is to add the constant as an extension to NSNib.Name:

extension NSNib.Name {
    public static let TagCellView = NSNib.Name("TagCellView")
}

Then your use is shorter:

let nib = NSNib(nibNamed: .TagCellView, bundle: nil)

This way you only enter the hardcoded string "TagCellView" once in your codebase. Everywhere else in your code you use MyNibs.TagCellView. If you rename the nib in Interface Builder, you only need to update one line of code instead of several.

Of course nothing prevents you from typing NSNib.Name("TagCellView") everywhere you need to reference that nib but the extra baggage may be incentive to create a constant.