I have a basic custom structure in Swift where I’m aware that using Any
for input types is not ideal due to the language’s statically typed nature. This approach bypasses the compiler’s type checking and can introduce errors and loss of type information.
However, I find myself needing to return Any
from functions like vectorAssoc
, such as in the case of VectorAssoc
‘s return type. Is there a way in Swift, without resorting to custom types or optionals, to specify that I am returning two specific types in a more descriptive manner than Any
? I considered using typealias
, but I struggled to make it work for two types.
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)]
// prints (4, 1)
let a = vectorAssoc(4, vec)
// prints false
let b = vectorAssoc(12, vec)
Since the function’s output may serve as another function’s input, any suggestions to improve this setup are appreciated!
Adrian is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.