Data Control

서버와의 데이터 연동시 Data Control

데이터모델을 구성하는 이유

Sample Code v0.1

import Foundation
struct UserModel {

    enum Gender: Int {
        case women = 1
        case men = 2
    }
    
    var userID: String
    var userPWD: String
    var email: String
    var birthday: String?
    var gender: Gender?
    
    init?(userDic:[String:Any]) {
        
        // Required Properties
        guard let userID = userDic["userID"] as? String else { return nil }
        self.userID = userID
        
        guard let userPWD = userDic["userPWD"] as? String else { return nil }
        self.userPWD = userPWD
        
        guard let email = userDic["email"] as? String else { return nil }
        self.email = email
        
        
        // Optional Properties
        self.birthday = userDic["birthday"] as? String
        
        if let gender = userDic["gender"] as? Int, (gender == 1 || gender == 2)
        {
            self.gender = Gender(rawValue: gender)
        }
        
    }
    
}

Sample Code v0.2

import Foundation
struct EventData {
    
    var imageURL: String
    var eventName: String
    var eventPlace: String
    var startDate: Date
    var endDate: Date
    
    init?(dataDic: [String:Any]) {
        guard let imageURL = dataDic["imageURL"] as? String else { return nil }
        self.imageURL = imageURL
        
        guard let eventName = dataDic["eventName"] as? String else { return nil }
        self.eventName = eventName
        
        guard let eventPlace = dataDic["eventPlace"] as? String else { return nil }
        self.eventPlace = eventPlace
        
        // Date 처리
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-mm-dd"
        
        guard let startDateStr = dataDic["startDate"] as? String else { return nil }
        guard let startDate = formatter.date(from: startDateStr) else { return nil }
        self.startDate = startDate
        
        guard let endDateStr = dataDic["endDate"] as? String else { return nil }
        guard let endDate = formatter.date(from: endDateStr) else { return nil }
        self.endDate = endDate
    }
}

위 코드에서 Date 만드는 법 뜯어보기

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd"

let startDateStr = dataDic["startDate"] as? String else { return nil }
let startDate = formatter.date(from: startDateStr) else { return nil }
self.startDate = startDate