I have a basic custom structure in Swift where using Any
for input types is less than ideal due to the language’s statically typed nature, which can bypass the compiler’s type checking and lead to errors and loss of type information.
However, I’ve encountered a need to return Any
from functions like vectorAssoc
, particularly for cases where the return type could be either a tuple or a boolean. Here’s an example of the Vector
and vectorAssoc
functions:
struct Vector<Element>: ExpressibleByArrayLiteral {
private var storage: [Element] = []
public init(arrayLiteral elements: Element...) {
storage = elements
}
func count() -> Int {
return storage.count
}
subscript(index: Int) -> Element {
return storage[index]
}
}
func vectorAssoc(_ v: Int, _ vec: Vector<(Int, Int)>) -> Any {
func helper(_ i: Int) -> Any {
if i >= vec.count() {
return false
} else {
let elem = vec[i]
if elem.0 == v {
return elem
} else {
return helper(i + 1)
}
}
}
return helper(0)
}
let vec: Vector = [(2, 1), (3, 1), (4, 1), (5, 1)]
// Example usage
let a = vectorAssoc(4, vec) // prints (4, 1)
let b = vectorAssoc(12, vec) // prints false
Since the output of vectorAssoc
may be used as input for another function, I’m seeking suggestions on how to handle the return type Any
more effectively. Ideally, I’m looking for a way to specify that the return type can only be one of two specific types (either a tuple or boolean) without resorting to custom types or optionals.
If there’s a method to transform such an Any
into a primitive type that takes advantage of Swift’s type safety features, I would greatly appreciate any insights or improvements to this setup.
—
So a very basic explanation for the new question is:
Any in this case is ONLY 2 types (tuple and boolean), it cannot be more than two. If there was a way to return Any(only two specific types) and somehow that Any will become a primitive type(one of those 2) that could take advantage of the type safety thing
Adrian is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1