How to Define a Variable in a Swift If Statement

Is it possible to define a variable in a Swift if statement?

No you can not. The if statement defines a local scope, so whatever variable you define inside its scope, won't be accessible outside of it.

You have a few options

var cellWidth = requiredWidth
if notification.type == "vote"{
cellWidth = maxWidth - 80
println("cellWidth is \(cellWidth)")
println("maxWidth is \(maxWidth)")
}
println("cellWidth is \(cellWidth)")

or (better IMHO) without using variable, but only constants

func widthForCell(_ maxWidth: CGFloat, _ requiredWidth: CGFloat, _ notification: Notification) -> CGFloat {
switch notification.type {
case "vote": return maxWidth - 80
default: return requiredWidth
}
}
let cellWidth = widthForCell(maxWidth, requiredWidth, notification)
println("cellWidth is \(cellWidth)")

Setting variable values via an IF statement in Swift

Instead of == you wrote = in your if statement, and by the way here's a shorter version of that code

let locValueDeterminer = Int.random(in: 0...1)

let loc1Value = locValueDeterminer == 0 ? 0.5 : 0.0
let loc2Value = 1.0

Asking what locValueDeterminer == 0 ? 0.5 : 0.0 means?-

it's equivalent to condition ? something : something else

So in a way it translates to:

if locValueDeterminer == 0{
loc1Value = 0.5
}else{
loc1Value = 0.0
}

Swift - using my variables in an if statement

Your commented code needs to be written as:

let doomsdayPerMonth: [Int:Int]
if remainder == 0 {
doomsdayPerMonth = [ 1:31, 2:28, 3:7, 4:4, 5:9, 6:6, 7:11, 8:8, 9:5, 10:10, 11:7, 12:12]
} else {
doomsdayPerMonth = [ 1:25, 2:29, 3:7, 4:4, 5:9, 6:6, 7:11, 8:8, 9:5, 10:10, 11:7, 12:12]
}

The problem with your version is that you declare local variables that have no scope outside of the if/else statement.


Please not that your entire weekday finding method can be written as:

func findDayOfWeek(_ month: Int, _ day: Int, _ year: Int) -> String {
let date = Calendar.current.date(from: DateComponents(year: year, month: month, day: day))!
let weekday = Calendar.current.component(.weekday, from: date)
let formatter = DateFormatter()

return formatter.weekdaySymbols[weekday - 1]
}

And here's your whole class with some rework. No need to hardcode month and weekday names.

class Birthday {
let formatter: DateFormatter = {
let fmt = DateFormatter()
fmt.dateStyle = .long
fmt.timeStyle = .none

return fmt
}()

func dayOfWeek(_ month: Int, _ day: Int, _ year: Int) -> String {
let date = Calendar.current.date(from: DateComponents(year: year, month: month, day: day))!
let weekday = Calendar.current.component(.weekday, from: date)

return formatter.weekdaySymbols[weekday - 1]
}

func writeInWords(_ month: Int, _ day: Int, _ year: Int) -> String {
let date = Calendar.current.date(from: DateComponents(year: year, month: month, day: day))!

return formatter.string(from: date)
}
}

let bd = Birthday()
print(bd.dayOfWeek(3, 24, 1914))
print(bd.writeInWords(1, 27, 2018))

Output:

Tuesday

January 27, 2018

How to create a var in an if statement with SwiftUI

Try to write the if/else as

let oldDateType = self.Bol ? self.OldDate.asDate : isNewDay

is it possible to set a variable value using an if statement?

You can use ternary operator in Swift

return height > 3.0 ? "giant" : "regular"

Also in Kotlin you can do

return if(height > 3.0) "giant" else "regular"

Is it possible to use a string variable in if condition in Swift?

You should use a comparison operator for this.

if myString == myFunc() { 
// your code
}

If statement always wants a condition that can return a bool value. i.e. true and false.

In your above code, you are not providing sufficient data to if statement so that it can calculate whether the result iss true or false.

When you compare it like if myString == myFunc() , if statement will compare the string and return true if string matches else false.

if the string matches, it will execute the code that is within if conditions scope. Otherwise it will calculate the else condition.

UPDATE1:

I see you have updated the question, so you want to check if myFunc() is empty or not?

For that you can compare it with empty string.

if myFunc() == "" { 
// your code
}

UPDATE2:

Question: (asked in comment) instead of writing "if(x == 1)" i am trying to use a variable so my if statement is "if(stringVaraible)" where stringVariable = "x ==1". Basically I am asking if it is possible to turn a string into normal code

Answer: No, you can't do that. Swift is a compiled language, not interpreted like Ajax. Read more here: https://stackoverflow.com/a/30058875/8374890

Swift 3: Set variable in if/else statement

In your code, the scope of error_msg is limited to the blocks within the if statement.
You could declare error_msg outside of the if blocks scope, e.g.

let response = parseJSON["message"] as? String
var error_msg:String

if response == "username_in_use" {
error_msg = "Username in already use!"
} else if response == "email_in_use" {
error_msg = "Email address in already use!"
} else {
error_msg = "Unknown Error!"
}

alertView.showTitle(
alertTitle: error_msg
)

How to make changes to a variable inside an if statement

This solution work well form me

 func checkIfFieldsEmpty()-> Bool{
var v = [
"name":""
]

var textfieldStatus:Bool = true
var fielderrorCount:Int = 0

for (key, value) in v{

if value == ""{
fielderrorCount = 1
}
}

if fielderrorCount > 0{
textfieldStatus = false

}

return textfieldStatus

}

Making a variable from if statement global

delclare jsonIsExistant at the place you want it. If you are making an iOS App, than above viewDidLoad() create the variable

var jsonIsExistant: String?

then at this point use it

do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String],
let tempJsonIsExistant = json["isExistant"] {
jsonIsExistant = tempJsonIsExistant
}
}

This could be rewritten like so though

do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
jsonIsExistant = json["isExistant"]
}
} catch {
//handle error
}

If handled the second way, then you have to check if jsonIsExistant is nil before use, or you could unwrap it immediately with a ! if you are sure it will always have a field "isExistant" every time that it succeeds at becoming json.

Set a @State var inside an If statement in Swift

You cannot put logic code like that inside your body -- all that you can have there is code that outputs a view.

So, you could do:

var body: some View {
if this > that {
Text("This")
} else {
Text("That")
}
}

because that results in a View (Text) getting rendered. In your example, though, you're just doing assignment.

That has to be done in a separate function or in a closure outside of what gets directly rendered in the view.

So:

func testThisThat() {
if this > that {
someVar = 1
}
}

var body: some View {
Button(action: {
testThisThat()
}) {
Text("Run test")
}
}

In the above, your logic runs in a closure outside the view hierarchy, and a Button gets rendered to the view.

If you give more specifics about what you're trying to do, perhaps the answer can be clarified, but that's the source of the error.

As suggested in the comments, you can also run logic code in onAppear, like this:

var body: some View {
VStack {
//view code
}.onAppear {
//logic
if this > that {
someVar = 1
}
}
}


Related Topics



Leave a reply



Submit