如何删除可选字符
let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex)
println(color) // Optional("Red")
let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
println(imageURLString)
//http://hahaha.com/ha.php?color=Optional("Red")
我只想输出“http://hahaha.com/ha.php?color=Red”
我能怎么做?
嗯....
实际上,当您将任何变量定义为可选时,您需要打开该可选值。要解决此问题,您必须将变量声明为非选项或在变量后面放置!(感叹号)标记以解包选项值。
var temp : String? // This is an optional.
temp = "I am a programer"
print(temp) // Optional("I am a programer")
var temp1 : String! // This is not optional.
temp1 = "I am a programer"
print(temp1) // "I am a programer"
我再次看了看这个,我简化了我的回答。我认为这里的大部分答案都忽略了这一点。您通常希望打印您的变量是否具有值,并且您还希望程序不会崩溃(如果不使用!)。这就是这个
print("color: \(color ?? "")")
这会给你空白或价值。
在尝试通过字符串插值使用它之前,需要打开可选项。最安全的方法是通过optional binding:
if let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex) {
println(color) // "Red"
let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
println(imageURLString) // http://hahaha.com/ha.php?color=Red
}
使用“!”检查nil和unwrap:
let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex)
println(color) // Optional("Red")
if color != nil {
println(color!) // "Red"
let imageURLString = "http://hahaha.com/ha.php?color=\(color!)"
println(imageURLString)
//"http://hahaha.com/ha.php?color=Red"
}
在swift3
,您可以轻松删除可选项
if let value = optionalvariable{
//in value you will get non optional value
}
除了其他答案中提到的解决方案,如果您想要始终避免整个项目的可选文本,您可以添加此pod:
pod 'NoOptionalInterpolation'
(Qazxswpoi)
pod添加了一个扩展来覆盖字符串插值init方法,以便一劳永逸地删除Optional文本。它还提供了一个自定义运算符*来恢复默认行为。
所以:
https://github.com/T-Pham/NoOptionalInterpolation
有关更多详细信息,请参阅此答案import NoOptionalInterpolation
let a: String? = "string"
"\(a)" // string
"\(a*)" // Optional("string")
。
使用var check:String?="optional String"
print(check!) //optional string. This will result in nil while unwrapping an optional value if value is not initialized or if initialized to nil.
print(check) //Optional("optional string") //nil values are handled in this statement
为我工作!