Isaac To
Isaac To

Reputation: 739

How to modify a struct object that is typed Any in Swift?

Is there a way to modify the x property of unknown in the following piece of code?

struct S {
    var x = 3
}

var s = S()

var unknown: Any = s

unknown is of type Any and a copy of s. While x of s can be modified by something likes s.x = 4, how can one modify the x of unknown?

Upvotes: 2

Views: 194

Answers (4)

Isaac To
Isaac To

Reputation: 739

At this point, I think modifying x of unknown directly is not possible in Swift and it doesn't has to be. After all, a struct object typed Any is always a copy of another object, there seems to be no need to modify the internals of such a copy for doing so doesn't modify the original.

I will mark this post as the answer to my question so that future readers will understand the situation clearly, but I will also up-vote all answers that are worthy of consideration.

Upvotes: 0

John Montgomery
John Montgomery

Reputation: 7096

You didn't specify a use case, but the only reason I can think of for doing this is if you wanted to be able to assign multiple different structs to unknown. In that case, a protocol might do what you need:

protocol HasX {
    var x: Int {get set}
}

struct S: HasX {
    var x = 3
}

var s = S()

var unknown: HasX = s

unknown.x = 4 // no error

This will limit you to only the properties required by HasX, but it's the only way I can think of to accomplish this without using a class.

Upvotes: 1

Alexander
Alexander

Reputation: 63272

You can use a conditional binding:

if var s = unknown as? S {
    s.x = 4
    unknown = s
}
else {
    print("unknown is not an S")
}

Upvotes: 3

Sandro
Sandro

Reputation: 84

Make a type cast: (unknown as S).x = 4

Upvotes: 0

Related Questions