Home > Software design >  There is any difference between the static property and static function in Swift
There is any difference between the static property and static function in Swift

Time:08-24

I want to know if there is any difference between any of these 2 declarations?

static var sessionConfiguration: URLSessionConfiguration = {
    let myConfig = URLSessionConfiguration.default
    let base64LoginString = EndpointController.getBase64StringLoginWithUserAndPasswordV2()
    myConfig.httpAdditionalHeaders = ["Authorization" : base64LoginString]
    return myConfig
}()
    
static func getURLSessionConfigurationDefault() -> URLSessionConfiguration {
    let myConfig = URLSessionConfiguration.default
    let base64LoginString = EndpointController.getBase64StringLoginWithUserAndPasswordV2()
    myConfig.httpAdditionalHeaders = ["Authorization" : base64LoginString]
    return myConfig
}

CodePudding user response:

In the var t = { }() syntax: the { } is a function that returns a value, and the () is calling that function once to set the initial value of the variable t. You can change t to something else later, because it's a var. That syntax is like var a = 42 but instead of 42 you set it to the result of running a function, like: { return 42 }() but that function isn't run every time you read (or write) the value t

The getURLSessionConfigurationDefault() -> URLSessionConfiguration is always creating a new instance of something and returning that new instance - the result of the function.

  • Related