0

I started learning to work with swift today.

Unfortunately I got an error by trying to return a boolean by a function which checks if there is a connection to a network.

import SwiftUI
import Network

let monitor = NWPathMonitor()

func CheckNetworkConnection() -> Bool {
    monitor.pathUpdateHandler = { path in
        if path.status == .satisfied {
            var connection = true
        } else {
            var connection = false
        }

        return connection //<--- Unexpected non-void return value in void function
    }
}

Thank you for everyone who can help!

Kai Zobel
  • 13
  • 4
  • This looks like an asynchronous call which is a strange choice to program something like that if it is your first day with swift. May I suggest you start reading [The Swift Programming Language](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html) book to learn the basics and then maybe start with something simpler for your first project. – Joakim Danielson Mar 31 '21 at 06:46
  • Does this answer your question? [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – Joakim Danielson Mar 31 '21 at 06:48

1 Answers1

1

First your connection variable only valid in {}, second the pathUpdateHandler is inal public var pathUpdateHandler: ((NWPath) -> Void)? so you can't return a Bool. Maybe you can change to something like thing

 func CheckNetworkConnection(completion: @escaping (Bool) -> Void) {
        monitor.pathUpdateHandler = { path in
            let connection = path.status == .satisfied ? true : false
            completion(connection)
        }
    }
goat_herd
  • 571
  • 3
  • 13
  • Thank you! The errors are gone but I don't understand how to get the result of the return? ````if CheckNetworkConnection(completion: <#T##(Bool) -> Void#>) = true {}````? – Kai Zobel Mar 31 '21 at 05:14
  • you should read more about closure, you will find the answer – goat_herd Mar 31 '21 at 05:43
  • using like below: CheckNetworkConnection { (connection) in if connection { ... } } – goat_herd Mar 31 '21 at 05:46