The “any” keyword in Swift

Paul O'Neill
4 min readMar 17, 2023

The Swift team has improved expressing generics in Swift by adding the “some” keyword which allows for converting this line of code:

func myFunc<P>() -> P where P: MyProtocol

to this:

func myFunc() -> some MyProtocol

Generics are great for expressing an opaque type. Meaning that the exact type doesn’t matter as long as it conforms to the given protocol. However, it must be one type and only one type.

What if I wanted to return different types for different states? For example, let’s use the Plottable protocol from the Charts framework. This protocol defines types that can be labeled and plotted on a chart. Values like String, Date, and Double all conform to Plottable. Consider the code below:

let myItemList: [MyItem] = [ ... ]

struct MyItem {
let title: String
let weight: Double
let startDate: Date

enum FilterType {
case title, weight, startDate
}

func getValue(of type: FilterType) -> some Plottable {
switch type {
case .title:
return self.title
case .weight:
return self.weight
case .startDate:
return self.startDate
}
}

Here’s what I’m trying to do: Above I have an array of items of type MyItem where I want to chart specific attributes based on the filter type. The getValue method gets…

--

--