Reputation: 2964
UserDefaults.standard.set(["a", "b"], forKey: "xxx")
if let def = UserDefaults.standard.array(forKey: "xxx") as? [String] {
print(def) // ["a", "b"]
}
if let def = UserDefaults.standard.array(forKey: "xxx") {
print(def) // [a, b]
}
In the second example, when you don't explicitly cast the array to [String]
(leaving it as [Any]
), the print console produces an array without quotation marks which suggests they aren't strings. What is happening here?
Upvotes: 1
Views: 145
Reputation: 9829
If you print out their types, you'll find that the second def
is an array of NSTaggedPointerString
s. NSTaggedPointerString
is a private subclass of NSString
, and NSString
s print out to the console without the double quotes when inside an array.
UserDefaults.standard.set(["a", "b"], forKey: "xxx")
if let def = UserDefaults.standard.array(forKey: "xxx") as? [String] {
print(def) // ["a", "b"]
print(type(of: def)) // Array<String>
for element in def {
print(element, "is a", type(of: element)) // a is a String
// b is a String
}
}
if let def = UserDefaults.standard.array(forKey: "xxx") {
print(def) // [a, b]
print(type(of: def)) // Array<Any>
for element in def {
print(element, "is a", type(of: element)) // a is a NSTaggedPointerString
// b is a NSTaggedPointerString
}
}
print(["a", "b"] as [NSString]) // [a, b]
Upvotes: 1
Reputation: 777
In the first example, you are optional unwrapping/inferring the array
to an array of strings. So it's logged as ["a", "b"]
which is the standard representation of string value in double-quotes.
In the second one, the type is not inferred so by default it's logged as an array of Any
type values where you don't see any double-quotes.
Upvotes: 0