4

Can anyone suggest how to solve this NSCollectionView issue? Converted from Swift 3 to Swift 4 and magic started happening :)

Code:

let item = NSNib(nibNamed: NSNib.Name(rawValue: "MACollectionViewItem"), bundle: nil)
collectionView.register(item, forItemWithIdentifier: "CollectionViewItem")

Error for the second line:

Cannot invoke 'register' with an argument list of type '(NSNib?, forItemWithIdentifier: String)'

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
spacecash21
  • 1,331
  • 1
  • 19
  • 41

1 Answers1

14

In Swift 4, you need to use NSUserInterfaceItemIdentifier instead of a String to identify a user interface element.

You should define static constants for identifiers and reference them when registering nibs.

Example:

extension NSUserInterfaceItemIdentifier {
    static let collectionViewItem = NSUserInterfaceItemIdentifier("CollectionViewItem")
}

collectionView.register(item, forItemWithIdentifier: .collectionViewItem)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • 2
    You can also define static constants for the identifiers, compare https://stackoverflow.com/a/45520652/1187415 for a similar issue. As I understand it, that is the recommended pattern. – Martin R Sep 26 '17 at 09:46
  • 1
    My point is that you can now define a NSUserInterfaceItemIdentifier static type property instead of a String constant. – Martin R Sep 26 '17 at 09:52
  • Thanks for such a swift answer! Love Swift after Objective C, Swift 3 was really good, but looks like Swift 4 is not getting easier :) – spacecash21 Sep 26 '17 at 10:15
  • @spacecash21: Did you notice that you already use the same technique in your `NSNib(nibNamed: NSNib.Name(rawValue:...))` ? – Martin R Sep 26 '17 at 11:14
  • Yes I did :) Change is inevitable, hard to adjust :D Will get used to it in a week or two :) – spacecash21 Sep 26 '17 at 12:23
  • This answer isn't working with whatever version of Swift is in Xcode 10. I get a compiler error: "Argument labels '(_:)' do not match any available overloads" – Bryan Oct 29 '18 at 06:52
  • @Bryan Just checked it, this still works with Swift 4.2. I'd suggest checking your syntax again. – Tamás Sengel Oct 29 '18 at 11:37
  • Thanks Tamás. The project's Swift version was incorrectly changed to 3, which is what caused this failure. It does indeed work in 4.2 – Bryan Oct 30 '18 at 06:45