How to Rewrite Swift ++ Operator in : Ternary Operator

How to rewrite Swift ++ operator in ?: ternary operator

How about:

column = (column >= 2) ? 0 : column+1

It looks like you might be doing something like clock arithmetic. If so, this gets the point across better:

column = (column + 1) % 2

Need help rewriting a bool as a ternary operator

You don't need to use ternary operators here, just writing this would be enough:

UIView.animate(withDuration: 0.5, animations: {
self.toolbar.isHidden = !self.toolbar.isHidden
self.textSlider.isHidden = !self.textSlider.isHidden
self.setNeedsStatusBarAppearanceUpdate()
}, completion: nil)

But I guess you are doing this to practice using the ternary operator, but please be aware that there are cases where the ternary operator is not useful at all. Not every if statement can be converted to one. e.g. this one:

if someCondition {
someAction1()
someAction2()
} else {
someActon3()
someAction4()
}

You can't write two statements as one of the operands of the ternary operator.

For the two lines in question, you can just follow the same logic you did with the above lines:

navigationController!.setNavigationBarHidden(isHidden ? false : true, animated: false)
isHidden = isHidden ? false : true // this is really redundant...

A more appropriate use case of the ternary operator is when you want to use different values of a non-Bool type depending on a condition. For example:

label.text = isHidden ? "I am hidden!" : "I am visible!"

How to set UIButton title using ternary operator in swift

You need to check against a Bool, not a string. If you add a variable to hold the state then you can do it with

class LoginVC: UIViewController{

@IBOutlet weak var changeOtpBtn: UIButton!
var shouldLoginWithEmail = false


override func viewDidLoad() {
super.viewDidLoad()

self.changeOtpBtn.setTitle(shouldLoginWithEmail ? "Login with Email" : "AELogin with phoneD", for: .normal)
}

If you want to see a larger example, Try this in a playground:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
var shouldLoginWithEmail = false

lazy var button: UIButton = {
UIButton()
}()

@objc func buttonClicked() {
print("tapped")
shouldLoginWithEmail.toggle()
setLoginButtonTitle()
}

func setLoginButtonTitle() {
button.setTitle(shouldLoginWithEmail ?
"Login with Email" :
"AELogin with phoneD",
for: .normal)
}


override func loadView() {
let view = UIView()
view.backgroundColor = .white

button.addTarget(self, action: #selector(buttonClicked),
for: .touchUpInside)
button.frame = CGRect(x: 100, y: 200, width: 200, height: 20)
button.setTitleColor(.blue, for: .normal)
setLoginButtonTitle()

view.addSubview(button)
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

Which shows the changing button title.

Sample Image

You should be able to get what you need from here.

Should I always replace if...then...else with a ternary in Swift?

Since both are valid and there is no difference in performance, the goal is readability.

Use a ternary conditional for a simple inline decision.

For anything that wouldn't be appropriate inline or more complicated than basic arithmetic, it would probably be more readable to use normal conditional statements

Apple has a great example of this in the Swift 2.2 docs

Examples from Swift 2.2 Apple docs:

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90

I would say the above is just as readable as below and much cleaner.

let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
rowHeight = contentHeight + 50
} else {
rowHeight = contentHeight + 20
}
// rowHeight is equal to 90

Ternary operator and unwrapping with SwiftLint

I would map the optional to the interpolated string, and use ?? to provide the default value:

let display = subtype.map { "\(rawValue) (\($0))" } ?? rawValue

Why is my Swift ternary operator not working?

The compiler needs a little help, the spaces in your ternary are causing it to get confused due to the way that operator precedence is implemented in the language. If you wrap your statements in parentheses then it will compile and do what you expect.

Also there is property that will allow you to check whether something is a multiple(of:), it can make for easier to read code, though you can use item % 2 == 0 if you wish and it will still work.

var list = [2, 4, 3, 6, 1, 9]

var sumOfEven = 0
var productOfOdd = 1

for item in list {
item.isMultiple(of: 2) ? (sumOfEven += item) : (productOfOdd *= item)
}

print(sumOfEven) // 12
print(productOfOdd) // 27

However, ternaries can make for harder to understand code. This would be better written as an if-else like you had written in your question.

for item in list {
if item % 2 == 0 { // you could use item.isMultiple(of: 2)
sumOfEven += item
} else {
productOfOdd *= item
}
}

Ternary operator issue SwiftUI

Break body construction for smaller components, like below

ForEach (expenses.items) { item in
self.listRow(for: item) // << extract !!
}
.onDelete(perform: removeItem)

,say, to private row generator function

private func listRow(for item: Item) -> some View { // << your item type here
HStack {
VStack(alignment: .leading) {
Text(item.name)
.font(.headline)
Text(item.type)
}
Spacer()
Text("€\(item.amount)")
Circle()
.frame(width: 10, height: 10)
.foregroundColor(item.amount < 10 ? Color.green : (item.amount < 100 ? Color.orange : Color.red))
}
}


Related Topics



Leave a reply



Submit