1

It seems that when you print() an enumeration type from the macOS SDK (and presumably others), it prints out the type name, but when you print from your own enum it prints out the case name.

In the below example, I would expect to see "security case: wpaPersonalMixed" rather than "security case: CWSecurity".

Is there a trick to getting this working?

import CoreWLAN

// Working example
enum Numbers: Int {
    case one = 1
}
print("number case: \(Numbers.one)") // "number case: one" <-- EXPECTED
print("number raw: \(Numbers.one.rawValue)") // "number raw: 1"

// Failing example
let wifiClient: CWWiFiClient = CWWiFiClient()
let interface: CWInterface = wifiClient.interface(withName: "en0")! // interface name is specific to my machine. YMMV
let security: CWSecurity = interface.security()
print("security case: \(security)") // "security case: CWSecurity" <-- PROBLEM
print("security raw: \(security.rawValue)") // "security raw: 3"

Swift 5.1 macOS SDK 10.4

Sulthan
  • 128,090
  • 22
  • 218
  • 270
Thomas
  • 5,736
  • 8
  • 44
  • 67
  • Possible duplicate of [Convert Objective-C enum to Swift String](https://stackoverflow.com/questions/35318216/convert-objective-c-enum-to-swift-string). – Martin R Oct 20 '19 at 19:38

1 Answers1

4

Because CWSecurity is declared in Objective-C and bridged to Swift.

Add the @objc attribute to expose the enum to Objective-C and the cases are gone.

@objc enum Numbers: Int {
    case one = 1
}

Objective-C enums are much more primitive than the native Swift ones.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • This is helpful and shows how cases can be removed from the working example. Is there no pattern for going the other way besides manually mapping every ObjC enum value to my own strings? – Thomas Oct 20 '19 at 21:20
  • 1
    Yep. By the way, https://www.youtube.com/watch?v=Aav96a2Ir78 (from part four of https://www.hackingwithswift.com/articles/166/xcode-tips-and-tricks-part-one) is a great way to make this super fast. So, create switch, use Xcode’s quick fix to add all the cases, get rid of the empty code blocks, and then edit all of the cases of the switch statement in one fell swoop (rather than cutting and pasting each case yourself). It’s a little tricky the first time you do this, but once you learn this “multiple cursors” technique (trick #32), you’ll love it. – Rob Oct 20 '19 at 22:27