스위프트 인라인 조건부?
Swift에서 어떻게합니까?
(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"))
출력 :
존재하지 않는 것
Swift 3에 도입 된 새로운 Nil-Coalescing 연산자를 사용할 수 있습니다 . 경우는 기본 값을 반환합니다 입니다 .someOptional
nil
let someValue = someOptional ?? ""
여기서 someOptional
가 nil
인 경우이 연산자는에 할당 ""
합니다 someValue
.
var firstBool = true
var secondBool: Bool
firstBool == true ? (secondBool = true) : (secondBool = false)
이 경우 secondBool을 firstBool이 무엇이든 변경합니다. 정수와 문자열로도 할 수 있습니다.
이를 " 삼항 연산자 "라고합니다.
@Esqarrouth의 답변과 관련하여 더 나은 형식은 다음과 같습니다.
스위프트 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
}
당신은 너무 가까웠습니다. 변수에 할당하기 만하면됩니다.
self.automaticOption = (automaticOptionOfCar ? "Automatic" : "Manual")
편집하다:
왜 같은식이 문자열에 포함될 수 없는지 아십니까?
다음과 같이 할 수 있습니다.
let a = true
let b = 1
let c = 2
println("\(a ? 1: 2)")
잘,
+ 연산자를 사용하여 조건부를 문자열과 연결하면 작동합니다.
따라서 Mike가 맞습니다.
var str = "Something = " + (1 == 1 ? "Yes" : "No")
내 프로젝트에서 사용한 간단한 솔루션
Swift 3+
var retunString = (state == "OFF") ? "securityOn" : "securityOff"
다음과 같이 인라인 조건부를 사용했습니다.
isFavorite 함수는 Boolen을 반환합니다.
favoriteButton.tintColor = CoreDataManager.sharedInstance.isFavorite(placeId: place.id, type: 0) ? UIColor.white : UIColor.clear
tourOperatorsButton.isHidden = place.operators.count != 0 ? true : false
참고 URL : https://stackoverflow.com/questions/26189409/swift-inline-conditional
'Nice programing' 카테고리의 다른 글
C ++의 클래스 선언 내에서 const 멤버 초기화 (0) | 2020.10.28 |
---|---|
DOM을 사용하여 기존 SVG에 SVG 요소 추가 (0) | 2020.10.28 |
Prolog의 좋은 초보자 자료 (0) | 2020.10.28 |
파일 이름 패턴으로 존재하는 파일 (0) | 2020.10.28 |
날짜가 datetime.today ()와 같은 날인지 어떻게 확인할 수 있습니까? (0) | 2020.10.28 |