简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM