I have an object that I would like to be indexable, just like an Array is, and then have a function return an 'Indexable' (this way, the function could return either an instance of my custom class, or an Array).
So, the use of a custom would be like so:
let myObject = MyObject()
myObject[0] = 8
let value = myObject[0]
print("value: \(value)")
// output should be:
// 'value 8'Step 1 is to make this object indexable:
Class MyObject
{
subscript(index: UInt16) -> UInt8 {
get
{
// return a value based on custom logic using the index
}
set
{
// set a value based on custom logic using the index
}
}
}Step 2 is to make sure Array can be indexed using the same values, so I have made an extension on Array to also be able to give me value based on UInt16 index, as my Arrays are [UInt8], the return element is UInt8
extension Array
{
subscript(index: UInt16) -> Element {
get
{
return self[Int(index)]
}
set(newValue)
{
self[Int(index)] = newValue
}
}
}Now here is the difficult part: I would like my function to return something like 'Indexable', so that a client of this function is unaware of whether the underlying type is an Array ([UInt8]), or an instance of MyObject:
func source(forValue value: UInt16) -> ???
{
/// switch on the value, and return either an instance of MyObject or Array
}However, I cannot use the already existsing 'Indexable' protocol, as the compiler will give me this error:
"Protocol 'Indexable' can only be used as a generic constraint because it has Self or associated type requirements".
I can read the Swift book and see why this is an error, but I have hard time figuring out what would another way to make this happen.
I cannot create my own protocol, and 'override' the subscripting on Array, as that will turn into a recursion.
Compare this to Objective-C, where I could simply implement the subscript methods, and use 'id' as type (not saying that is the better way, but it seems in Obj-C you could always just fall back to id, which is not safe, but would work if you were carefull, and in Swift we are at the other end of the spectrum: because all code has to be fully typed, things like this that should be easy, are now really hard to accomplish, and are a distraction from the actual task I want to do).
So the quesion is: how to mix custom objects with Array such that a function can return a type that indicates only that this type can be indexed?