본문 바로가기

swift

Codable 활용하여 함수 만들기

   static func readFile<T: Codable>(fileUrl:URL, decodeData: T.Type) -> T? {
        do {
            let data = try Data(contentsOf: fileUrl)
            let decoder = JSONDecoder()
            let result = try decoder.decode(T.self, from: data)
            
            return result
        } catch {
            print("JSON : \(error.localizedDescription)")
            return nil
        }
    }
let bundleJson = MyFileManager.readFile(fileUrl: bundleUrl, decodeData: [[QuestionData]].self)

 

어떤 타입을 넣어도 
그 타입이 배열로 감싸져 잇어도 디코딩이 가능하다.

static func writeFile<T: Codable>(fileUrl: URL, data: T, complete:(Bool) -> Void) {
        do {
            let encoder = JSONEncoder()
            encoder.outputFormatting = .prettyPrinted // 보기 좋게 저장 (선택사항)
            
            let encodedData = try encoder.encode(data)
            try encodedData.write(to: fileUrl)
            
            print("파일 저장 성공: \(fileUrl)")
            complete(true)
        } catch {
            print("JSON 저장 실패: \(error.localizedDescription)")
            complete(false)
        }
    }

어떤 타입도 인코딩 가능