1

Let's assume we have a custom type given by

struct S {
    let value_1: UInt = 1
    let value_2: UInt = 2
} 

and I want to create a Double array (e.g. [1.0, 2.0]) using a cast:

let s = S()
let a = s as Array<Double> // fails obviously

The final goal is to call

func aMethod(array: [Double]) { ... }

in a convient way:

let s = S()
aMethod(s)

My first idea was to use

extension S {
    // but how to continue here?
}

Any ideas of solving this in an elegant way without a static method?

1 Answer 1

2

You could add an array property to the Struct, for example:

struct S {
    let value_1: UInt = 1
    let value_2: UInt = 2
    var array: [UInt] {
        return [value_1, value_2]
    }
}

let s = S()
let a = s.array  // [1, 2]

An extension also works:

struct S {
    let value_1: UInt = 1
    let value_2: UInt = 2
}

extension S {
    var array: [UInt] {
        return [value_1, value_2]
    }
}

let s = S()
let a = s.array  // [1, 2]

And why not a protocol:

protocol HasArray {
    var value_1: UInt { get }
    var value_2: UInt { get }
    var array: [UInt] { get }
}

extension HasArray {
    var array: [UInt] {
        return [value_1, value_2]
    }
}

struct S: HasArray {
    let value_1: UInt = 1
    let value_2: UInt = 2
}

let s = S()
let a = s.array  // [1, 2]
Sign up to request clarification or add additional context in comments.

4 Comments

I assume there is no way for methodExpectingADoubleArray(s), because there is no implicit conversion in Swift, right?
Mm, I'm not sure I understand your question. Do you mean duck typing like in Ruby?
Actually no, more in the direction of implicit conversion. But I think this is not possible, right?
Indeed, I think doing it exactly how you want isn't possible in Swift.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.