빠른 인라인 조건부?
스위프트에서 이걸 어떻게 하나요?
(someboolexpression ? "Return value 1" : "Return value 2")
(아니요, 아직 설명서 전체를 읽지 않았습니다...아마 2페이지에서 놓쳤을 거예요!)
91페이지에 나와 있는 것이 맞으니 위의 내용이 맞는 것 같습니다.그러나 나는 이것을 다음과 같은 문자열로 사용하려고 합니다.
println(" some string \(some expression ? "Return value 1" : "Return value 2")"
하지만 컴파일러는 행복하지 않습니다.가능하다면 이것이 가능한지 아십니까?
이것은 제가 할 수 있는 한 가까이에 있습니다.
let exists = "exists"
let doesnotexist= "does not exist"
println(" something \(fileExists ? exists : doesnotexist)")
그렇게 하기 위해 원라이너를 찾고 있다면, 당신은 그것을 끌 수 있습니다.?:문자열 보간 및 연결을 통한 연산+대신:
let fileExists = false // for example
println("something " + (fileExists ? "exists" : "does not exist"))
출력:
존재하지 않는 것
스위프트 3에 도입된 새로운 닐 병합 연산자를 사용할 수 있습니다.다음과 같은 경우 기본값을 반환합니다.someOptional이라nil.
let someValue = someOptional ?? ""
여기, 만약에someOptional이라nil이 연산자가 할당합니다.""로.someValue.
var firstBool = true
var secondBool: Bool
firstBool == true ? (secondBool = true) : (secondBool = false)
이 경우 두 번째 Bool을 첫 번째 Bool이 무엇이든 변경합니다.정수와 문자열로도 이 작업을 수행할 수 있습니다.
그것은 "3차 연산자"라고 불립니다.
@Esqarrough의 답변과 관련하여, 저는 더 나은 형식이 될 것이라고 생각합니다.
스위프트 3:
var firstBool = true
var secondBool: Bool
secondBool = firstBool ? true : false
이는 다음과 같습니다.
var firstBool = true
var secondBool: Bool
if (firstBool == true) {
secondBool = true
} else {
secondBool = false
}
프로젝트에 사용한 간단한 솔루션
스위프트 3+
var retunString = (state == "OFF") ? "securityOn" : "securityOff"
너무 가까우셨군요.변수에 할당하기만 하면 됩니다.
self.automaticOption = (automaticOptionOfCar ? "Automatic" : "Manual")
편집:
왜 같은 표현이 문자열에 포함될 수 없는지 아십니까?
할 수 있습니다.
let a = true
let b = 1
let c = 2
println("\(a ? 1: 2)")
음.
+ 연산자를 사용하여 조건부를 문자열과 연결하면 작동합니다.
그러므로 마이크가 맞습니다.
var str = "Something = " + (1 == 1 ? "Yes" : "No")
나는 다음과 같은 인라인 조건부를 사용해 왔습니다.
IsFavorite 함수가 Booleen을 반환합니다.
favoriteButton.tintColor = CoreDataManager.sharedInstance.isFavorite(placeId: place.id, type: 0) ? UIColor.white : UIColor.clear
tourOperatorsButton.isHidden = place.operators.count != 0 ? true : false
다중 조건의 경우 다음과 같이 작동할 수 있습니다.
let dataSavingTime: DataSavingTime = value == "0" ? .ThirtySecs : value == "1" ? .Timing1 : .Timing2
if 및 ternary 연산자가 없는 한 줄 조건
let value = "any"
// set newValue as true when value is "any"
let newValue = value == "any"
print(newValue)
//answer: true
언급URL : https://stackoverflow.com/questions/26189409/swift-inline-conditional
'programing' 카테고리의 다른 글
| Node.js console.log 대 console.info (0) | 2023.08.25 |
|---|---|
| 자바스크립트에서 TCP 소켓을 통해 통신하려면 어떻게 해야 합니까? (0) | 2023.08.25 |
| Angular 2에서 템플릿 내의 유형 주조 (0) | 2023.08.25 |
| 부트스트랩 2를 사용하는 일부 위치에서는 글리피콘의 색상을 파란색으로 변경합니다. (0) | 2023.08.25 |
| exec("mysqdump")에서 2를 반환하지만 명령줄에서 명령이 작동합니다. (0) | 2023.08.25 |