bandoy123
bandoy123

Reputation: 243

How can I output this function to be a simple string?

I am trying to get access to the private IP in my app and I have the following code which gets the local IP and returns it. The issue is that it is returning a [String] not String and every time I try and use it I get an error. Here is the code (from How to get Ip address in swift):

func getIFAddresses() -> [String] {
    var addresses = [String]()

    // Get list of all interfaces on the local machine:
    var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
    if getifaddrs(&ifaddr) == 0 {

        // For each interface ...
        for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
            let flags = Int32(ptr.memory.ifa_flags)
            var addr = ptr.memory.ifa_addr.memory

            // Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
            if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {

                    // Convert interface address to a human readable string:
                    var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
                    if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
                        nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                            if let address = String.fromCString(hostname) {
                                addresses.append(address)
                            }
                    }
                }
            }
        }
        freeifaddrs(ifaddr)
    }
    print(addresses)


    return addresses
}

and here is how I am trying to use it:

self.privateIp.title = getIFAddresses()

However when I do this, I get an error:

Cannot assign a value of type "[String]" to a value of type "String".

If I try and cast it like this:

self.privateIp.title = getIFAddresses() as! String

I get the following error:

Cast from '[String]' to unrelated type 'String' always fails.

Upvotes: 1

Views: 170

Answers (1)

Greg
Greg

Reputation: 25459

[String] is an array of string so it can contain more than one item. If you want first element from the array you can use:

if let ipAdd = getIFAddresses().first {
    self.privateIp.title = ipAdd
}

It's equivalent to getIFAddresses()[0] but more safety because if the array is empty call to getIFAddresses()[0] will crash your app.

You can call last to get the last one or you can enumerate all of the items inside the array.

Upvotes: 2

Related Questions