Println Dictionary Has "Optional"

Initialize a dictionary with non-optional empty arrays in Swift

When you access a dictionary with:

let x = dframe["pine"]

The compiler didn't know if you pass a valid key to the dictionary, if you didn't, it will return nil. The optional part is not in the array initialization, but in the value search of the dictionary.

Unwrapping Optional Type Any from Dictionary

Those are coming in as strings, not numbers - try something like:

monsterMinSpeed = (settings["monsterMinSpeed"] as? NSString)?.doubleValue ?? 0.0

Why does SWIFT print Optional(...)

Swift has optional types for operations that may fail. An array index like airports["XYZ"] is an example of this. It will fail if the index is not found. This is in lieu of a nil type or exception.

The simplest way to unwrap an optional type is to use an exclamation point, like so: airports["XYZ"]!. This will cause a panic if the value is nil.

Here's some further reading.

You can chain methods on option types in Swift, which will early exit to a nil without calling a method if the lefthand value is nil. It works when you insert a question mark between the value and method like this: airports["XYZ"]?.Method(). Because the value is nil, Method() is never called. This allows you to delay the decision about whether to deal with an optional type, and can clean up your code a bit.

To safely use an optional type without panicking, just provide an alternate path using an if statement.

if let x:String? = airports["XYZ"] {
println(x!)
} else {
println("airport not found")
}

How to print a string from plist without Optional ?

One way to get rid of the Optional is to use an exclamation point:

println(todayTitle!)

However, you should do it only if you are certain that the value is there. Another way is to unwrap and use a conditional, like this:

if let theTitle = todayTitle {
println(theTitle)
}

Paste this program into runswiftlang for a demo:

let todayTitle : String? = "today"
println(todayTitle)
println(todayTitle!)
if let theTitle = todayTitle {
println(theTitle)
}

How to write Dictionary extension that handles optional values

You could do this with reflection. Doesn't require much more code than you already have:

extension Dictionary
{
func someMethod()
{
for (key, value) in self
{
var valueRef = _reflect(value)

while valueRef.disposition == .Optional && valueRef.count > 0 && valueRef[0].0 == "Some"
{
valueRef = valueRef[0].1
}

if let valueString: String = valueRef.value as? String
{
print(" \(key) = \(valueString)")
}
else
{
print(" \(key) = \(value) cannot be cast to `String`")
}
}
}
}

let dictionary: [String : AnyObject?] = ["foo" : "bar"]
dictionary.someMethod()

Returns

foo = bar

let dictionary: [String : AnyObject?] = ["foo" : nil]
dictionary.someMethod()

Returns

foo = nil cannot be cast to `String`

let dictionary: [String : AnyObject?] = ["foo" : UIViewController()]
dictionary.someMethod()

Returns

foo = Optional(<UIViewController: 0x7fee7e819870>) cannot be cast to `String`

NSDictionary returning an optional integer when retrieving information

The Optional(1) value just means that the value is an optional swift type.

You can unwrap the value from an optional using the ! operator.

let a = friendLetterCount["a"]! as Int
println(a)

a will the unwrapped value.

You can also use optional binding to check for nil while also doing unwrapping.

if let a = friendLetterCount["a"] as? Int
{
println(a)
}

Please learn about Optionals from Apple's Swift Book.

Also you can read articles like this
http://www.appcoda.com/beginners-guide-optionals-swift/

Printing a dictionary value in Swift

If you know that the key is there, you can print the value with an exclamation point:

var airports = ["ALB":"Albany International", "ORD": "O'Hare"]
println(airports["ALB"]) // Prints Optional("Albany International")
println(airports["ALB"]!) // Prints Albany International

If you are not sure that the key is there, and you would like to avoid an error, you can do this:

if let alb = airports["ALB"] {
print(alb)
}

Function print will be called only when "ALB" key is present in the dictionary, in which case alb would be assigned a non-optional String.

Any? to Dictionary Cast and retrieving value

println(paramValue as Dictionary) won't work because dictionary is type-safe.

You could use:

println(paramValue as [String : Int])

if those will always be the right types.

If they might change, use optional casting (as? instead of as).



Related Topics



Leave a reply



Submit