0

I´m new to Swift development and have following problem:

I making rest calls via Alamofire to get data from an REST API but if I set a class property to one of the returned values, it doesnt work. defaultBotId is still an empty string after the rest calls completes.

If I look at the console, it shows the right string that should be set to that variable print("Closure: ", defaultBot.defaultBotId)

It seems to me, that is not possible to change a class property if I`m inside a closure or whats the problem here?

Here is my code from SinusbotSDK.swift

import Foundation
import Alamofire

public class SinusbotSDK {
    let host: String
    let username: String
    let password: String
    var defaultBotId: String
    
    public init(host: String, username: String, password: String, defaultBotId: String = "") {
        self.host = host
        self.username = username
        self.password = password
        self.defaultBotId = defaultBotId
    }
    
    public func fetchDefaultBotId() {
        AF.request(self.host + "/api/v1/botId")
            .validate()
            .responseDecodable(of: DefaultBot.self) {
                response in guard let defaultBot = response.value else {return}
                self.defaultBotId = defaultBot.defaultBotId
                print("Closure: ", defaultBot.defaultBotId)
            }
    }
    
    public func printVar() {
        print(self.defaultBotId)
    }
}

And here is the code where I call fetchDefaultBotId() and printVar() printVar shows no value because the string is still empty

import SwiftUI
import SinusbotSDK

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
        
        Button(action: {
            let sinusbot = SinusbotSDK(host: "myHost", username: "myUser", password: "myPassword")
            
            sinusbot.fetchDefaultBotId()
            sinusbot.printVar()
        }){
            Text("Press me")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
  • 1
    You’re making a asynchronous call, the print method is called before the property has been set. – Joakim Danielson Nov 25 '20 at 19:19
  • "If I look at the console, it shows the right string that should be set to that variable print("Closure: ", defaultBot.defaultBotId)" Indeed, BUT ask your this, does the `print()` inside `printVar()` is called BEFORE or AFTER `print("Closure: ", defaultBot.defaultBotId)`? That's a important part of the understanding that you are missing the asynchrone concept. – Larme Nov 25 '20 at 19:29

0 Answers0