Reputation: 36
am new to swift PL. I have doubt regarding a new implementation. Your help would be appreciated. Thanks.
Desc : I have an enum in a class with multiple API URLs. Those API URL are accessing a variable - BaseURL
declared in that same class. I want to change value of that BaseURL
from another class but enum variables are fetching the same old value.
class : API.swift
var BaseURL = "xyz.com/"
enum apis {
static let login = BaseURL + "login"
}
class : ViewControllerA.swift
func switchBaseURL() {
BaseURL = "abc.com/"
// Call API Method
self.callAPI()
}
func callAPI(){
print("\(apis.login)") // Result is : xyz.com/login
}
I want to implement a solution that would enable to switch the value of BaseURL
anytime from any class such that enum fetches the latest value set in BaseURL everytime.
Upvotes: 0
Views: 864
Reputation: 2285
The problem here is that login
is declared static
. It means that it's only computed once. Not to mention, it's also let
.
One of the things that you can do without drastically changing your design is to modify the login
property to be computed every time it's accessed:
var baseURL = "xyz.com/"
enum API {
static var login: String { baseURL + "login" }
}
print(API.login) // xyz.com/login
baseURL = "abc.com/"
print(API.login) // abc.com/login
The code adopted to the original snippet:
var baseURL = "xyz.com/"
enum API {
static var login: String { baseURL + "login" }
}
func switchBaseURL() {
baseURL = "abc.com/"
callAPI()
}
func callAPI(){
print("\(API.login)")
}
switchBaseURL() // Prints abc.com/login
Upvotes: 2