swift 3 - ios : convert anyObject to string
Asked Answered
W

5

23

How could we convert anyobject to string in swift 3, it's very easy in the older version by using.

var str = toString(AnyObject)

I tried String(AnyObject) but the output is always optional, even when i'm sure that AnyObject is not a optional value.

Willpower answered 14/10, 2016 at 13:34 Comment(0)
P
44

The compiler suggests that you replace your code with:

let s = String(describing: str)

One other option is available if you have a situation where you want to silently fail with an empty string rather than store something that might not originally be a string as a string.

let s =  str as? String ?? ""

else you have the ways of identifying and throwing an error in the answers above/below.

Pelmas answered 14/10, 2016 at 16:20 Comment(0)
F
15

Here's three options for you:

Option 1 - if let

if let b = a as? String {
    print(b) // Was a string
} else {
    print("Error") // Was not a string
}

Option 2 - guard let

guard let b = a as? String
else {
    print("Error") // Was not a string
    return // needs a return or break here
}
print(b) // Was a string

Option 3 - let with ?? (null coalescing operator)

let b = a as? String ?? ""
print(b) // Print a blank string if a was not a string
Florey answered 14/10, 2016 at 13:47 Comment(0)
B
8

Here's a simple function (repl.it) that will mash any value into a string, with nil becoming an empty string. I found it useful for dealing with JSON that inconsistently uses null, blank, numbers, and numeric strings for IDs.

import Foundation

func toString(_ value: Any?) -> String {
  return String(describing: value ?? "")
}

let d: NSDictionary = [
    "i" : 42,
    "s" : "Hello, World!"
]

dump(toString(d["i"]))
dump(toString(d["s"]))
dump(toString(d["x"]))

Prints:

- "42"
- "Hello, World!"
- ""
Basement answered 7/9, 2019 at 0:51 Comment(0)
P
2

Try

let a = "Test" as AnyObject
guard let b = a as? String else { // Something went wrong handle it here }
print(b) // Test
Polygamy answered 14/10, 2016 at 13:37 Comment(0)
F
0

try this -

var str:AnyObject?
str = "Hello, playground" as AnyObject?
if let value = str
{
   var a = value as! String
}

OR

var a = str as? String
Flatling answered 14/10, 2016 at 13:35 Comment(1)
You have to make sure that AnyObjecthas a value if you´re using as! otherwise it will crash.Polygamy

© 2022 - 2024 — McMap. All rights reserved.