Home > AI > Language > Swift >

Object type transfer (map)

Example 1: use map to transfer the object type

struct SampleDTO: Codable{
    var id: Int
    var name: String
    var title: String
    var position: String { return String(id) + name }
}

struct SampleModel: Identifiable {
    var id: Int
    var name: String
    var position: String
    
    init(dto: SampleDTO) {
        self.id = dto.id
        self.name = dto.name
        self.position = dto.position
    }
}

let s1 = SampleDTO(id: 1, name: "mary", title: "student")
let s2 = SampleDTO(id: 2, name: "peter", title: "tutor")
let result = [s1, s2].map(SampleModel.init)
print(type(of: result[0]))
print(result[0].id)

Leave a Reply