Ternary operators in swift

0

Is it possible to do operadores ternarios in swift ?

I have this type of code that I repeat many times, and I wanted to know if I can simplify it using operadores ternarios . condicion ? resultadoTrue : resultadoFalse

if fechaHasta != "" {
    labelFecha.text = fechaHasta
}
    
asked by 17.11.2016 в 14:18
source

3 answers

2

Without knowing much about swift, I think what you need is this:

question ? answer1 : answer2

Example:

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)

Instead of:

let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
    rowHeight = contentHeight + 50
} else {
    rowHeight = contentHeight + 20
}

Source:

link

    
answered by 17.11.2016 в 14:23
0

Yes, in fact, it is equal to many languages that also use them (PHP for example). For your example it would be:

print(fechaHasta != "" ? labelFecha.text = fechaHasta : "lo que quieras poner si es falso")

I've put the function print so you can see it in the console but you could match it without problems to a variable.

    
answered by 17.11.2016 в 14:26
0

Claro is easy

var fecha = ""
fecha = fecha == "" ? labelFecha.text = "no hay fecha" : labelFecha.text = fechaHasta

Compare fecha equals empty string, if true labelFecha.text say "no date", : mean "otherwise" labelFecha.text equals variable fechaHasta .

    
answered by 23.06.2017 в 04:34