简体   繁体   中英

Swift dictionary as property does not init

I have a class which has a swift dictionary as internal variable.

   class OAuth: NSObject {

    public var oauthParameters:[String:String]
    public var SignatureSecret:String

    public var accessToken:String? = nil
    public var tokenSecret: String? = nil

    public init(consumerKey:String, consumerSecret:String, accessToken:String?, tokensecret:String?){

        self.oauthParameters = ["oauth_signature_method" : "SHA1"]

        if accessToken{
            self.oauthParameters.updateValue(accessToken!, forKey: "oauth_token")
        }

        if tokensecret{
            self.SignatureSecret = "\(consumerSecret)&\(tokensecret!)"
        }
        else {
            self.SignatureSecret = "\(consumerSecret)&"
        }

    }
}

I would like to assign some keys of the dictionary in function of the passed arguments, but the problem is that the variable oauthParameters does not retain the values passed as literals :(

EDIT: I guessed the dictionary was not initialzed because LLDB printed me out an empty dictionary (Xcode6B4) wehereas a println confirms all were ok.

It looks like your initializer isn't complete. For some reason the Playground isn't giving me an actual error, but you need to give self.SignatureSecret a value before exiting init() :

public init(consumerKey:String, consumerSecret:String, accessToken:String?, tokensecret:String?)
{
    self.oauthParameters = ["oauth_signature_method" : "SHA1"]
    self.SignatureSecret = String()
}

Once that's fixed I can see the values in self.oauthParameters :

println(o.oauthParameters["oauth_signature_method"]!)
// prints "SHA1"

It loos like you need to initialize oauthParameters
try something like this:

public var oauthParameters: [String: String] = [String: String]()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM