iOS랑 친해지기

[iOS] JSON 배열의 인덱스마다 구조가 다른 데이터 파싱 (옵셔널)

데브킹덕 2023. 8. 2. 14:49

Word of the day API에서 랜덤한 문자를 받고 싶었다.

https://rapidapi.com/jayantur13/api/word-of-the-day2

 

Word of the day API Documentation (jayantur13) | RapidAPI

 

rapidapi.com

 

 

Postman으로 Get 형식으로 데이터를 받아왔을 경우 JSON형태가 다음과 같았다.

[ ] 문자로 시작해 배열로 확인하였고 첫번째인덱스에만 info라는 이름을 가지는 객체가 있었고,

나머지 인덱스에는 source,date,word,type,mean라는 이름을 가진 객체가 있었다.

 


[
    {
        "info": "Note: This API doesn't gaurantee latest data by date."
    },
    {
        "source": "#1",
        "date": "Tuesday, August 01, 2023",
        "word": "zhuzh",
        "type": "unvailable",
        "mean": "to make something more lively and interesting, stylish, or appealing, as by a small change or addition."
    },
    {
        "source": "#2",
        "date": "August 1, 2023",
        "word": "",
        "type": "noun",
        "mean": "Perquisite refers to something extra that someone receives in addition to regular pay for doing a job."
    }
]

 

 

어떻게 구조체를 작성해야할지 고민하다가 문득 옵셔널을 모두 붙이면 어떻게 될까라는 생각을 했다.

있을 수도 있고 없을 수도 있으니까..

struct WordData: Codable{
    let info: String?
    let source: String?
    let date: String?
    let word: String?
    let type: String?
    let mean: String?
}

 

옵셔널 언래핑 잘해서 사용하면 될듯하다