swift 3 - ios:将 anyObject 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40044507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
swift 3 - ios : convert anyObject to string
提问by Anthony Shahine
How could we convert anyobject to string in swift 3, it's very easy in the older version by using.
我们如何在 swift 3 中将 anyobject 转换为字符串,在旧版本中使用非常容易。
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.
我试过了,String(AnyObject)
但输出总是可选的,即使我确定 AnyObject 不是可选值。
回答by sketchyTech
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.
否则,您可以在上面/下面的答案中识别和抛出错误。
回答by Ben
Here's three options for you:
这里有三个选项供您选择:
Option 1 - if let
选项 1 - 如果让
if let b = a as? String {
print(b) // Was a string
} else {
print("Error") // Was not a string
}
Option 2 - guard let
选项 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
Option 3 - let with ?? (null coalescing operator)
选项 3 - 让与 ?? (空合并运算符)
let b = a as? String ?? ""
print(b) // Print a blank string if a was not a string
回答by Rashwan L
Try
尝试
let a = "Test" as AnyObject
guard let b = a as? String else { // Something went wrong handle it here }
print(b) // Test
回答by Trevor Robinson
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.
这是一个简单的函数(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"]))
Prints:
印刷:
- "42"
- "Hello, World!"
- ""
回答by Anupam Mishra
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