Is it possible to coerce IPAddress to IPv4Address

I’m using the swift-asynchrony-dns-resolver.

The queryA method returns an array of ARecords each of which contains an IPAddress.

IPAddress is an abstract protocol with two conforming protocols, IPv4Address and IPv6Address.

I expect a v4 but I’ve run out of ideas on how to do the coercion. My latest attempt was

If let v4 = ipaddress as IPv4Address {
// do my thing here
}


But this gives the error “Cannot convert value of type ‘IPAddress’ to type ‘IPv4Address’ in coercion.

and

> If let v4 = ipaddress as? IPv4Address {
>       // do my thing here
> }

gives Cast from 'IPAddress' to unrelated type 'IPv4Address' always fails
Ideas?

An “as?” cast should work.

Can you show how ipaddress is declared, including its type annotation?

IPAddress is an enum, with two cases for IPv4 vs IPv6. There are no IPv4Address or IPv6Address types defined in that package…?

I assume you're referring to swift-async-dns-resolver. Looking at the code in that repository, I see that IPAddress is an enum with two cases (each with associated type String), not a protocol, and I don't see any type or protocol named IPv4Address.

Can you clarify?

Apple documentation for IPAddress

1 Like

Ah, that documentation refers to a different library. Two libraries can define distinct types or protocols with the same name. If you're using swift-async-dns-resolver, then IPAddress isn't a protocol but an enum.

If you want to convert between AsyncDNSResolver.IPAddress and Network.NWEndpoint.IPv4Address, then you're going to have to destructure the IPAddress value to get the string value and use that to initialize the IPv4Address value.

2 Likes

fyi, we recently indexed docs for swift-async-dns-resolver on swiftinit.

1 Like