Skip to content

Instantly share code, notes, and snippets.

struct Apartment : Codable {
var buildingName : String
var rent : Float
var address : Address
}
struct Address : Codable {
var flatNumber : Int
var streetName : String
var city : String
var state : String
var country : String
}
func createAppartmentToRent(){
let oxfordAptAddress = Address(flatNumber: 24, streetName: "Elphinston Road", city: "Pune", state: "Maharashtra", country: "India")
let oxfordApt = Apartment(buildingName: "Oxford", rent: 18500.0, address: oxfordAptAddress)
}
/**
To convert an apartment object to JSON string.
returns : JSON string for the respective apartment object
*/
func convertToJSON(apartmentInfo: Apartment) -> String?{
let encoder = JSONEncoder()
if let encodedApt = try? encoder.encode(apartmentInfo){
func getAptJSON() -> String {
let bravuriaAptJSON = "{\"address\":{\"state\":\"UP\",\"flatNumber\":24,\"city\":\"Kanpur\",\"streetName\":\"MH Area\",\"country\":\"India\"},\"buildingName\":\"Bravuria\",\"rent\":18500}"
return bravuriaAptJSON
}
/**
Converts a JSON String to it's corresponding object
params : aptJSON -> The JSON string which needs to be decoded
returns: Apartment object keeping JSON string as Datasource
*/
func decodingJSONToApartment(aptJSON : String) -> Apartment?{
print("\n\nDECODING DATA")
if let aptJsonData = aptJSON.data(using: .utf8) {