[swift] Swift에서 ObjectMapper를 사용하여 객체의 필수 속성 검증하기

Swift에서 ObjectMapper는 매우 강력한 json 매핑 및 객체 직렬화 라이브러리입니다. ObjectMapper를 사용하면 JSON 데이터를 Swift 객체로 변환하거나 Swift 객체를 JSON으로 변환하는 작업을 쉽게 수행할 수 있습니다.

하지만 때때로 우리는 필수 속성의 값이 제공되었는지 확인해야 할 때가 있습니다. 이를 위해 ObjectMapper에는 기능이 내장되어 있지는 않지만, 몇 가지 방법을 사용하여 필수 속성의 검증을 수행할 수 있습니다.

ObjectMapper에서 필수 속성 검증 방법

  1. JSON 데이터에서 Swift 객체로 변환하기 전에 ObjectMapper에서 제공하는 JSON 메서드를 사용하여 필수 속성이 있는지 확인할 수 있습니다.
import ObjectMapper

struct Person: Mappable {
    var name: String?
    var age: Int?

    init?(map: Map) {}

    mutating func mapping(map: Map) {
        name <- map["name"]
        age <- map["age"]
    }

    func validate() -> Bool {
        guard let _ = name else {
            return false
        }
        return true
    }
}

let jsonString = "{\"name\":\"John\",\"age\":30}"
let person = Mapper<Person>().map(JSONString: jsonString)

if let person = person {
    if person.validate() {
        print("Valid person object")
    } else {
        print("Missing required properties")
    }
}
  1. ObjectMapper의 shouldIncludeNilValues 옵션을 사용하여 필수 속성을 포함하지 않은 경우 객체 매핑을 거부할 수 있습니다. 이를 위해서는 Mapper 객체를 생성할 때 shouldIncludeNilValues 속성을 false로 설정해야 합니다.
let mapper = Mapper<Person>(shouldIncludeNilValues: false)
let person = mapper.map(JSONString: jsonString)
  1. 객체가 생성된 후에 필수 속성의 값이 있는지 확인할 수도 있습니다. 예를 들어, 생성자에서 필수 속성을 검증하거나, 객체의 메서드를 사용하여 필수 속성을 확인할 수 있습니다.
struct Person {
    var name: String
    var age: Int

    init?(name: String?, age: Int?) {
        guard let name = name, !name.isEmpty else {
            return nil
        }
        guard let age = age else {
            return nil
        }

        self.name = name
        self.age = age
    }

    func hasRequiredProperties() -> Bool {
        return !name.isEmpty
    }
}

let person = Person(name: "John", age: 30)

if let person = person, person.hasRequiredProperties() {
    print("Valid person object")
} else {
    print("Missing required properties")
}

위와 같은 방법을 사용하여 ObjectMapper를 사용하는 동안 필수 속성의 존재 여부를 확인할 수 있습니다. 필수 속성 검증은 데이터의 일관성을 유지하는 데 중요한 역할을 합니다.