dbus dbus - 2 years ago 144
Swift Question

How can I look up the local computer name in swift?

I am trying to return a string of the local computer name (as shown in sharing in system preferences).

I have found this method in objective-c but i'm unsure how I can convert this to swift and set a string variable to the returned value.

[[NSHost currentHost] localizedName];

If anyone could help that would be great!

Thanks :)

Answer Source


Xcode 8 beta • Swift 3

let currentHost = Host.current().localizedName ?? ""

NSHost locazizedname property returns an optional String. You can use if let or "??" nil coalescing operator to unwrap the String returned:

let currentHost = NSHost.currentHost().localizedName ?? ""
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download