Random User Generator | Home の APIを叩き、JSON形式で帰ってきたレスポンスを Swiftの構造体に収めるサンプル。 Playgroundで動作確認。
import Foundation struct RandomUserResult : Codable { var results : [User] var info : Info struct User : Codable { var gender : String var name : Name var location : Location var email : String var login : Login var dob : Dob var registered : Registered var phone : String var cell : String var id : Id var picture : Picture var nat : String struct Name : Codable { var title : String var first : String var last : String } struct Location : Codable { var street : Street var city: String var state: String var country : String var postcode: Int var coordinates : Coordinates var timezone : Timezone struct Street : Codable { var number : Int var name : String } struct Coordinates : Codable { var latitude: String var longitude: String } struct Timezone : Codable { var offset: String var description: String } } struct Login : Codable { var uuid : String var username : String var password : String var salt : String var md5 : String var sha1 : String var sha256 : String } struct Dob : Codable { var date : String var age : Int } struct Registered : Codable { var date : String var age : Int } struct Id : Codable { var name : String var value : String } struct Picture : Codable { var large : String var medium : String var thumbnail : String } } struct Info :Codable { var seed : String var results: Int var page : Int var version : String } } let apiurl = URL(string: "https://randomuser.me/api/")! var request = URLRequest(url: apiurl) request.addValue("json", forHTTPHeaderField: "dataType") URLSession.shared.dataTask(with: request) {data, response, err in if (err == nil) { print ("(゚∀゚) API通信成功") let jsonStr = String(data: data!, encoding: .utf8)! do { let result : RandomUserResult = try JSONDecoder().decode(RandomUserResult.self, from: jsonStr.data(using: .utf8)!) print (result) } catch { print (error.localizedDescription) } } else { print ("(´・ω・`) API通信失敗") } }.resume()