swift 3 - ios:将anyObject转换为字符串

Ant*_*ine 14 string ios swift anyobject

我们如何在swift 3中将anyobject转换为字符串,在旧版本中使用它非常容易.

var str = toString(AnyObject)
Run Code Online (Sandbox Code Playgroud)

我试过String(AnyObject)但输出总是可选的,即使我确定AnyObject不是可选值.

ske*_*ech 31

编译器建议您用以下代码替换代码:

let s = String(describing: str)
Run Code Online (Sandbox Code Playgroud)

如果您希望使用空字符串静默失败而不是将最初可能不是字符串的字符串存储为字符串,则可以使用另一个选项.

let s =  str as? String ?? ""
Run Code Online (Sandbox Code Playgroud)

否则你有办法在上面/下面的答案中识别和抛出错误.


Ben*_*Ben 11

这里有三个选项:

选项1 - 如果让

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

选项2 - 保护让

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
Run Code Online (Sandbox Code Playgroud)

选项3 - 让?? (null合并运算符)

let b = a as? String ?? ""
print(b) // Print a blank string if a was not a string
Run Code Online (Sandbox Code Playgroud)


Tre*_*son 5

这是一个简单的函数(repl.it),它将任何值混搭为一个字符串,并nil成为一个空字符串。我发现它对于处理不一致地使用null、空白、数字和数字字符串作为 ID 的JSON 很有用。

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"]))
Run Code Online (Sandbox Code Playgroud)

印刷:

- "42"
- "Hello, World!"
- ""
Run Code Online (Sandbox Code Playgroud)