Bool var inside a if statement

Hi.
So now i ran into a new problem.
I can't set a bool value to var in a if statement, pretty sure i'm missing something.

let udpArr = dataStr.split(separator: " ")
if (remoteHost == "192.168.10.31"){
if (udpArr[0] == "BankList"){
Hz11 = String(udpArr[2])
Hz12 = String(udpArr[3])
Hz13 = String(udpArr[4])
Hz14 = String(udpArr[5])
connected = true
}
else if (udpArr[0] == "Frequency"){
print(udpArr[3])
returnCh11 = false
returnCh12 = false
returnCh13 = false
returnCh13 = false
if (Int(udpArr[3]) == 1) {
print("1")
returnCh11 = true }
else if (Int(udpArr[3]) == 2) {
print("2")
returnCh12 = true }
else if (Int(udpArr[3]) == 3) {
print("3")
returnCh13 = true }
else if (Int(udpArr[3]) == 4) {
print("4")
returnCh14 = true }
}
}

All the best

Finn

You have to help us out a bit here. What variable are you trying to set that's causing a problem? What's its declaration and where? What's the compiler error message you're getting?

You should also format the code block properly using Markdown syntax, and (if you're asking us to figure things out for you) make sure the code you give compiles as-is.

I sure will.
The statements, is in a func, and the varilbles are being used by view, to show diff status.

Here is the full func., the var connected is working fine, but the rest of them are not, i can't change value on them inside the if statement.
The var connected is working fine, and if i set the returnCh outside the if statement, it's fine,

func setView(dataStr: String){
let udpArr = dataStr.split(separator: " ")
if (remoteHost == "192.168.10.31"){
if (udpArr[0] == "BankList"){
Hz11 = String(udpArr[2])
Hz12 = String(udpArr[3])
Hz13 = String(udpArr[4])
Hz14 = String(udpArr[5])
connected = true
}
else if (udpArr[0] == "Frequency"){
print(udpArr[3])
returnCh11 = false
returnCh12 = false
returnCh13 = false
returnCh13 = false
if (Int(udpArr[3]) == 1) {
print("1")
returnCh11 = true }
else if (Int(udpArr[3]) == 2) {
print("2")
returnCh12 = true }
else if (Int(udpArr[3]) == 3) {
print("3")
returnCh13 = true }
else if (Int(udpArr[3]) == 4) {
print("4")
returnCh14 = true }
}
}
if (remoteHost == "192.168.10.32"){
print("(remoteHost) (dataStr)")
if (udpArr[0] == "BankList"){
Hz21 = String(udpArr[2])
Hz22 = String(udpArr[3])
Hz23 = String(udpArr[4])
Hz24 = String(udpArr[5])
connected = true
}
else if (udpArr[0] == "Frequency"){
returnCh21 = false
returnCh22 = false
returnCh23 = false
returnCh23 = false
if (Int(udpArr[3]) == 1) {
returnCh21 = true}
if (Int(udpArr[3]) == 2) {
returnCh22 = true}
if Int(udpArr[3]) == 3 {
returnCh23 = true}
if Int(udpArr[3]) == 4 {
returnCh24 = true}
}
}
if (remoteHost == "192.168.10.33"){
print("(remoteHost) (dataStr)")
if (udpArr[0] == "BankList"){
Hz31 = String(udpArr[2])
Hz32 = String(udpArr[3])
Hz33 = String(udpArr[4])
Hz34 = String(udpArr[5])
connected = true
}
else if (udpArr[0] == "Frequency"){
print(udpArr[3])
returnCh31 = true
returnCh32 = false
returnCh33 = false
returnCh33 = false
if (Int(udpArr[3]) == 1) {
returnCh31 = true}
if (Int(udpArr[3]) == 2) {
returnCh32 = true}
if (Int(udpArr[3]) == 3) {
returnCh33 = true}
if (Int(udpArr[3]) == 4) {
returnCh34 = true}

        }
}
print(returnCh11)
print(returnCh12)
print(returnCh13)
print(returnCh14)


return

   /////////////////////// Update view ? ///////////////////////

}

You’ve only caught the end of your code with the formatting.
Try enclosing the whole thing in three backticks. (See ‘fences’ section in the link below.)

https://markdown-it.github.io/

My english is nor good enough, to understand exatly how an what i should show.
But i wil give it one more go :-) and hope i learned something

Receiver file.

func listenUDP(port: NWEndpoint.Port) {
let withHost: NWEndpoint.Host = host1
let inPort: NWEndpoint.Port = port
let parameters = NWParameters.udp
let updateLed = false
let connection1 = NWConnection(host: withHost, port: inPort, using: parameters)
do {
parameters.allowLocalEndpointReuse = true

        self.Receiving = try NWListener(using: parameters, on: inPort)
        self.Receiving?.stateUpdateHandler = { [self](newState) in
            switch newState {
            case .ready:
                print("Listner ready")
                self.receive(on: connection1)
            case .failed:
                print("Listner failed")
            case .cancelled:
                print("Listner cancelled")
            default:
                
                break
            }
        }
        print("Vi kom vel hertil")
        self.Receiving?.newConnectionHandler = {(newConnection) in
            newConnection.stateUpdateHandler = {newState in
                switch newState {
                case .ready:
                    print("new connection establish")
                    
                    self.receive(on: newConnection)
                case .failed:
                    print("new connection failed")
                case .cancelled:
                    print("new connection cancelled")
                default:
                    
                    break
                }
            }
            newConnection.start(queue: DispatchQueue(label: "new client"))
        }
    } catch {
        print("unable to create listener")
    }
    Receiving?.start(queue: .global())
}

func receive(on connection: NWConnection) {
    connection.receiveMessage { (data, context, isComplete, error) in
        if !isComplete {
            print("Not Complete")
        }
        if let error = error {
            print("Error in Receive: - ",error)
            return
        }
        if let data = data, !data.isEmpty {
            switch(connection.endpoint) {
            case .hostPort(let inIP, _):
                remoteHost = "\(inIP)"
                
            default:
                break
            }
            let udpStr = String(decoding: data, as: UTF8.self)
           
            
   /////////////////////// Sort incomming data  //////////////////////////////////////////////////////////
            setView(dataStr: udpStr)
            DispatchQueue.main.async {
                self.updateLed = true
            }
        }
        
        self.receive(on: connection)
        
    }
}

}

My function file i have a seperate file for the function

//
//  SetView.swift
//  Sennheiser G3
//
//  Created by Finn Hansen on 18/04/2024.
//

import Foundation

///Receied upd packet, are saed to /dataStr is formatet like this   Frequency    123456   21   1
///the address: Frequency
///the Frequency: i.e. 123456
///the bank : i.e. 21
///the ch.: 1...4

func setView(dataStr: String){
    let udpArr = dataStr.split(separator: " ")
    if (remoteHost == "192.168.10.31"){
        if (udpArr[0] == "BankList"){
            Hz11 = String(udpArr[2])
            Hz12 = String(udpArr[3])
            Hz13 = String(udpArr[4])
            Hz14 = String(udpArr[5])
            connected = true
            }
        else if (udpArr[0] == "Frequency"){
            returnCh11 = false
            returnCh12 = false
            returnCh13 = false
            returnCh13 = false
            print("Channel   \(udpArr[3])") //Prints "Channel   1"
            if (Int(udpArr[3]) == 1) {
                print("1")
                returnCh11 = true }
            else if (Int(udpArr[3]) == 2) {
                print("2")
                returnCh12 = true }
            else if (Int(udpArr[3]) == 3) {
                print("3")
                returnCh13 = true }
            else if (Int(udpArr[3]) == 4) {
                print("4")
                returnCh14 = true }
            }
    }
    if (remoteHost == "192.168.10.32"){
        print("\(remoteHost)     \(dataStr)")
        if (udpArr[0] == "BankList"){
            Hz21 = String(udpArr[2])
            Hz22 = String(udpArr[3])
            Hz23 = String(udpArr[4])
            Hz24 = String(udpArr[5])
            connected = true
            }
        else if (udpArr[0] == "Frequency"){
            returnCh21 = false
            returnCh22 = false
            returnCh23 = false
            returnCh23 = false
            if (Int(udpArr[3]) == 1) {
                returnCh21 = true}
            if (Int(udpArr[3]) == 2) {
                returnCh22 = true}
            if Int(udpArr[3]) == 3 {
                returnCh23 = true}
            if Int(udpArr[3]) == 4 {
                returnCh24 = true}
            }
    }
    if (remoteHost == "192.168.10.33"){
        print("\(remoteHost)     \(dataStr)")
        if (udpArr[0] == "BankList"){
            Hz31 = String(udpArr[2])
            Hz32 = String(udpArr[3])
            Hz33 = String(udpArr[4])
            Hz34 = String(udpArr[5])
            connected = true
            }
        else if (udpArr[0] == "Frequency"){
            print(udpArr[3])
             returnCh31 = true
            returnCh32 = false
            returnCh33 = false
            returnCh33 = false
            if (Int(udpArr[3]) == 1) {
                returnCh31 = true}
            if (Int(udpArr[3]) == 2) {
                returnCh32 = true}
            if (Int(udpArr[3]) == 3) {
                returnCh33 = true}
            if (Int(udpArr[3]) == 4) {
                returnCh34 = true}
            
            
            }
    }
    print(returnCh11)
    print(returnCh12)
    print(returnCh13)
    print(returnCh14)
    
   
    return
    
       /////////////////////// Update view ? ///////////////////////
}

My problem is in this part

>  print("Channel   \(udpArr[3])") //Prints "Channel   1"
>            if (Int(udpArr[3]) == 1) {

It never returns true, but if change it to

if (Int(udpArr[2]) == 21) {

it returns true, so my suspetion goes to spilt()

Just format code for readability with syntax highlight:

let udpArr = dataStr.split(separator: " ")
if (remoteHost == "192.168.10.31"){
    if (udpArr[0] == "BankList"){
        Hz11 = String(udpArr[2])
        Hz12 = String(udpArr[3])
        Hz13 = String(udpArr[4])
        Hz14 = String(udpArr[5])
    connected = true
} else if (udpArr[0] == "Frequency") {
    // ... and so on

The code you are providing is almost impossible to understand, it has no indentation at all. Use built-in features:

That will make much easier to understand the problem you have.

These two lines are not equivalent: first prints description of the udpArr[3], the second performs conversion to Int of whatever is in the position of 3, which might result in different value or even nil.

I have tried to many things, also to put udpArr[3], into a var, without any luck.
if i change it to

>  print("Channel   \(udpArr[3])") //Prints "Channel   1"
>            if (Int(udpArr[2]) == 21) {

the if statement returns true, but i need to use udpArr[3]

could it somthing to do with

let udpArr = dataStr.split(separator: " ")

i have tried to use dataStr.components, also without any luck

could it be some kind of format error?

I cannot help with your current problem, but let me give a few pointers that may lead you towards the solution.

You seem to be receiving some kind of BanklList and FrequencyData from different IP addresses and then parse it to few dozen variables. This is not a good solution, you will stumble to the amount of variables and trying to do several things at once.

I would propose you find a way to organise the data in a bit more structured way. This will help you to divide and conquer the problem space, separating different parts of code in smaller parts that are easier to test and debug.

To me it looks like the main entities are Host, FrequencyPacket and BanklistPacket. One way to model this might be following.

struct Host {
    var name: String
    var returnCh1, returnCh2, returnCh3, returnCh4: Bool
}

class Packet { }

class FrequencyPacket: Packet {
    let frequency, bank, ch: Int
    init(frequency: Int, bank: Int, ch: Int) {
        self.frequency = frequency
        self.bank = bank
        self.ch = ch
    }
}

class BanklistPacket: Packet {
    let hz1, hz2, hz3, hz4: String
    init(hz1: String, hz2: String, hz3: String, hz4: String) {
        self.hz1 = hz1
        self.hz2 = hz2
        self.hz3 = hz3
        self.hz4 = hz4
    }
}

You should parse one packet at a time something like following and write tests that ensure your parsing code.

func parse(string: String) -> Packet? {
    let data = string.split(separator: " ")

    let packageType = data[0]
    switch packageType {
    case "BankList":
        return BanklistPacket(
            hz1: String(data[2]),
            hz2: String(data[3]),
            hz3: String(data[4]),
            hz4: String(data[5]))
    case "Frequency":
        guard 
            let frequency = Int(data[2]),
            let bank = Int(data[3]),
            let ch = Int(data[4])
        else { return nil }
        return FrequencyPacket(frequency: frequency, bank: bank, ch: ch)
    default:
        return nil
    }

When you have parsed the data in an easier to handle form, and have your Hosts stored in an array or such. The probability of getting forward increases.

Disclaimer: I did not think this fully thru nor test. And I may have misunderstood your project.

2 Likes

As @Seurahepo suggested, it would be beneficial for you to add some parsing into structs. That will allow to have clearer understanding what goes wrong, more likely isolating issue to the parsing at some point.

The string splitting should be fine as long as string looks exactly as in sample. If it eventually contains something that might prevent parsing it as Int, but not explicit - that might be an issue. I would also consider parsing raw Data (or even [UInt8]), if there is a high volume of data expected.

Sorry for been clear, but i have been so focused on the if statement.

Im receiving packets, from 3 different hosts.

I want to use , different values form this packets, to change bacground color on som buttons.
in the "BankList" section i receive frequencies, and place the first 4 into Hz1 ..... Hz4, in order to later use this data to change channel.
To change channel i send out a packet, and the host returns a packet (Frequency, Hz, BankNumber, Preset)

The Preset is been used to change backGroundColor.

this is a part of my view
HStack() {

                VStack(spacing: 5) {
                    
                    Text("Søren")
                        .frame(width: 300, height: 40)
                        .font(.system(size: 30))
                        .foregroundColor(.white)
                        .background(.clear)
                    
                    DualButton(title: "Xplorer", subtitle: "\(Hz11)", action: {UDPConnection1.sendUDP1("Frequency \(Hz11) 21 1\r")})
                        .background(returnCh11 ? Color.green : Color.cyan)
                        .buttonStyle(CustomBlueButton())
                    
                    DualButton(title: "Mustang", subtitle: "\(Hz12)", action: {UDPConnection1.sendUDP1("Frequency \(Hz12) 21 2\r")})
                        .background(returnCh13 ? Color.green : Color.cyan)
                        .buttonStyle(CustomBlueButton())
                    
                    DualButton( title: "", subtitle: "\(Hz13)", action: {UDPConnection1.sendUDP1("Frequency \(Hz13) 21 3\r")})
                        .background(returnCh13 ? Color.green : Color.cyan)
                        .buttonStyle(CustomBlueButton())
                       
                    
                    DualButton( title: "", subtitle: "\(Hz14)", action: {UDPConnection1.sendUDP1("Frequency \(Hz14) 21 4\r")})
                        .background(returnCh14 ? Color.green : Color.cyan)
                        .buttonStyle(CustomBlueButton())
                    
                    Divider()
                    Button(action: {}, label: {
                        Text("Mute")
                            .frame(width: 300.0, height: 100)
                            .foregroundColor(.white)
                            .padding(EdgeInsets(top: 2, leading: 4, bottom: 2, trailing: 4))
                    }).buttonStyle(MuteButton())
                    Divider()
                    Button(action: {print("New Button Clicked")}, label: {
                        Text("Midi Bypass")
                            .frame(width: 300.0, height: 100)
                            .foregroundColor(.white)
                            .padding(EdgeInsets(top: 2, leading: 4, bottom: 2, trailing: 4))
                    }).buttonStyle(MidiButton())
                }
                .padding(40)

Blockquote

Hi @FinnHansen,

To help people read your code in these forums, as others have suggested above, please use the Markdown formatting features. For example, when you have a block of code, type ``` on a separate line before and after your code so that it is formatted with syntax highlighting. The result looks like this:

print("Hello, world!")

When you are referring to code within a sentence, you can also help readers to understand by using a single backtick (`) before and after the code. It looks like this: "My variable named foo is set to true."

Try to present specifically the piece of code that you are having trouble with. This can be difficult to do, but if there is not enough information to understand your question, or if there is too much information to understand your question, it will be difficult for readers to help you. Indicate what error you are getting and where you are getting it, and explain what you expect to happen. If you are having trouble expressing yourself in English, chances are that there are people who can read your first language.

My BAD

Thanks for all your time,

It's now working for me, it turnes out that udpArr is not one but 1\r, which i actully know, from the SennHeiser dokumentation.
Sp now i just have strip the line shift, from the incomming packets.

Again thanks

1 Like