Constructing NWEndpoint from String, UInt16

NWConnection requires a host & port, as NWEndpoint.Host and NWEndpoint.Port types. This works great if you are passing "1.2.3.4" and 5678 as literals, but my values are coming from a configuration file. I cannot figure out out to pass String, UInt16 to init() OR to create NWEndpoint components.

Code Block
// This works
let c = NWConnection(host: "1.2.3.4", port: 1234, using: .udp)
// This does not
let host: String = parameters.dataGWIP
let port: UInt16 = parameters.dataGWPort
let c = NWConnection(host: host, port: port, using: .udp)

The error I get is:

Cannot convert value of type 'String' to expected argument type 'NWEndpoint.Host'
Answered by OOPer in 665173022
In Swift, NWEndpoint.Host is a ExpressibleByStringLiteral type, so String literals can be automatically converted, but not the same as String.
As well, NWEndpoint.Port is ExpressibleByIntegerLiteral, but not UInt16.

You can write something like this:
Code Block
let host: NWEndpoint.Host = NWEndpoint.Host(parameters.dataGWIP)
let port: NWEndpoint.Port = NWEndpoint.Port(rawValue: parameters.dataGWPort)!
let c = NWConnection(host: host, port: port, using: .udp)

(You can omit some type annotations if you prefer. And care about force unwrapping (!) of port.)
Accepted Answer
In Swift, NWEndpoint.Host is a ExpressibleByStringLiteral type, so String literals can be automatically converted, but not the same as String.
As well, NWEndpoint.Port is ExpressibleByIntegerLiteral, but not UInt16.

You can write something like this:
Code Block
let host: NWEndpoint.Host = NWEndpoint.Host(parameters.dataGWIP)
let port: NWEndpoint.Port = NWEndpoint.Port(rawValue: parameters.dataGWPort)!
let c = NWConnection(host: host, port: port, using: .udp)

(You can omit some type annotations if you prefer. And care about force unwrapping (!) of port.)
Excellent. One problem was that in the callers module where I was trying to create NWEndPoint.*, I was importing NetworkExtension instead of Network
Constructing NWEndpoint from String, UInt16
 
 
Q