선택적 문자열 문자를 제거하는 방법
선택적 문자를 제거하려면 어떻게합니까
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 ?? "")")
이것은 공백 또는 값을 제공합니다.
옵션을 문자열 보간을 통해 사용하기 전에 언 래핑해야합니다. 가장 안전한 방법은 선택적 바인딩을 사용하는 것입니다 .
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을 확인하고 "!"를 사용하여 풀기 :
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 'NoOptionalInterpolation'
( https://github.com/T-Pham/NoOptionalInterpolation )
포드는 확장을 추가하여 문자열 보간 init 메서드를 재정 의하여 선택적 텍스트를 모두 한 번 제거합니다. 또한 기본 동작을 다시 가져 오는 사용자 지정 연산자 *를 제공합니다.
그래서:
import NoOptionalInterpolation
let a: String? = "string"
"\(a)" // string
"\(a*)" // Optional("string")
자세한 내용은 https://stackoverflow.com/a/37481627/6390582에 대한 답변 을 참조하십시오.
이 시도,
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
Go with first if you are confident to have no nil in your variable.
print("imageURLString = " + imageURLString!)
just use !
참고URL : https://stackoverflow.com/questions/26347777/swift-how-to-remove-optional-string-character
'program story' 카테고리의 다른 글
내용을 감싸지 않는 이미지보기 (0) | 2020.12.06 |
---|---|
R 테이블에 해당하는 파이썬 (0) | 2020.12.06 |
스트림에서 instanceof 확인 (0) | 2020.12.06 |
__utma는 무엇을 의미합니까? (0) | 2020.12.05 |
R을 사용하여 등고선지도 오버레이로 3D 표면도 플로팅 (0) | 2020.12.05 |