Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return specific property when accessing a Struct without referencing its name

Tags:

swift

swiftui

Is there a way in Swift that I can get a property from a struct without having to reference it?

For example

public struct ASValue<T: Hashable>: Hashable {
    private let id = UUID()
    public var item: T
    
    public init(item: T) {
        self.item = item
    }
}

let val = ASValue(item: "Example")

print(val) // Prints: Example
like image 514
Joe Scotto Avatar asked Oct 22 '25 05:10

Joe Scotto


1 Answers

It's possible by adopting CustomStringConvertible and constraining T also to CustomStringConvertible

public struct ASValue<T: Hashable>: Hashable, CustomStringConvertible where T: CustomStringConvertible {
    
    private let id = UUID()
    public var item: T
    
    public var description : String {
        return "\(item)"
    }
}

let val = ASValue(item: "Example")

print(val) // Prints: Example

And this is a struct, the init method is for free.

like image 168
vadian Avatar answered Oct 24 '25 10:10

vadian