[swift-users] Implementing += for optional arrays

Rick Mann rmann at latencyzero.com
Thu Oct 20 19:17:47 CDT 2016

When working with URLComponents query items, it would be nice to write code like this:

var oqi: [URLQueryItem]? = [..., ..., ...]

var comps = URLComponents(…)
comps.queryItems += oqi

The problem is that queryItems is [URLQueryItem]?, and so I can't just append. I'd like to write a version of += that:

• Takes an LHS of [URLQueryItems]?, RHS of [things possibly derived from URLQueryItem]?
• if LHS != nil, make an array of LHS, and optionally append RHS, and return that
• if LHS == nil && RHS != nil, return RHS
• If both are nil, return nil

I'd like to do this in a generic way that works for any type on the left and possibly-dervied types on the right.

Rick Mann
rmann at latencyzero.com

More information about the swift-users mailing list