Reputation: 322
I have a defined a class that reads in a Dictionary from a file:
import Foundation
class Orte_c {
var meineOrte = NSDictionary()
init() {
if let path = NSBundle.mainBundle().pathForResource("mySites", ofType: "plist") {
let x = NSDictionary(contentsOfFile: path)
meineOrte = x!
}
}
} // end Orte_c
The plist-file was created by an objective-c app and is a dictionary where key and value are strings. This seems to work, but when I attempt to access the contents of this dictionary I get keys that read Optional(mykeytext) instead of only mykeytext . When looking up the value corresponding to a key, I get Optional(myvaluestring) instead of only myvaluestring. Hence my question: How do I get rid of this Optional()-clause? Its definitely not in my plist-file.
@IBAction func meinTest(sender: AnyObject) {
let x = mO.meineOrte // mO is defined as var mO = Orte_c()
print("x includes \(x.count) elements")
var key: String; var vs: String;
let enumerator: NSEnumerator = x.keyEnumerator()
key = String(enumerator.nextObject())
while key != "nil" {
vs = String(x.valueForKey(key))
print("key:" + key + " size:\(key.characters.count)" + " value:" + vs )
key = String(enumerator.nextObject())
}
}
The obvious would be to use key! and/or vs! - but this produces compilation errors.
Upvotes: 0
Views: 257
Reputation: 285072
Swift has more effective ways to enumerate a dictionary
let x = mO.meineOrte as! [String:String] // mO is defined as var mO = Orte_c()
print("x includes \(x.count) elements")
for (key, value) in x {
print("key:" + key + " value:" + value )
}
Upvotes: 2