add sum Specific value In Swift using for loop how it achieve using higher order function in swift

** i want to find sum of particular element in array. this is my code which is working find but i want achieve this using Higher order function in Swift how i can get **

 let arrData = [2,5,7,6,9,-9,10]     let arr = arrData.sorted { $  0>$  1     }     for i in 0...arr.count-1{         for j in 1..<arr.count-1{             if arr[i] + arr[j] == 17{                  print(arr[i] + arr[j])                 return             }          }     } 

How to call anonymous functions in swift

I am not an expert in iOS or swift. I want to call two anonymous functions of a class. They are like listeners. Below is my code:

let streamChannel = FlutterEventChannel(name: "com.sagar.no_plugins/channelDemo", binaryMessenger: controller)     streamChannel.setStreamHandler({         //onCancel(args: Any?)->FlutterError        //onListen(args: Any?, sink: EventSink?) -> FlutterError     }) 

How can I call these two methods which I have commented?

Setting a variable out of Do-Try Block [Swift]

I need to set a variable such that I can access it out of the do-try block. I use the do-try to exit early if there are any errors. This is what I currently use, but I am not sure that it is the best-practise or if there is any other better way to do it.

let rulesXml: XMLElement     do {         rulesXml = try XMLElement(xmlString: rules.string)     } catch let error {         self.showWarning(message: "Unable to create XML from the LRML Statements. Please validate the statements and try again.\nError: \(error)", title: "Error : LRML File Merge")         return nil     } 

Of course, I could use guard try? but then I cannot access the error message.

how to fetch particular role data names from json file swift [on hold]

[ {     "id": 7,     "role": "risk_owner",     "Name": "Sushma rana" }, {     "id": 8,     "role": "risk_owner",     "Name": "lal amt" }, {     "id": 41,     "role": "risk_moderator",     "Name": "username lastname" }, {     "id": 42,     "role": "control_owner",     "Name": "user 2"}] 

The above API Response I want to get name’s who all are having ‘role’ of “risk_owner and control owner”

private func updateActionOwnerFunction(){     for index in 0..<rideList.count{         let json = rideList[index] as! JSON         if (json["role"].stringValue.contains ("risk_tracker_action_owner control_owner risk_tracker_moderator risk_moderator risk_tracker_owner")){                  actionOwnerName.append(json["Name"].stringValue)         }else{             print("not role")         }             setupActionOwnerDropDown()        } 

** I tried this way not useful help me **

Разработка на swift на минимальном бюджете в 2019

Пишу вам по одному вопросу. Хочу начать изучение swift. Бюджет маленький не больше 500$ . Посоветуйте какую технику взять за эти деньги чтобы апгрейднуть и жить спокойно года 2-3.

Nil error when loading an image previously saved from remote notification Swift 4

I have this function that saves the picture from attachment url coming with the remote notification. It’s declared and called inside the didReceive delegate method of NotificationService.swift, but when I then load that picture in didReceive response to use it with other values from userInfo I get back nil. The Idea is to save it to file from NotificationService.swift so I don’t have to download it again when user tap on an action button..but I really think I’m not saving it correctly. Can you why it fails to save it? Also, Why I don’t see the prints from that function?

Saving Function:

func saveImage(imageName: String, image: UIImage) {               guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }              let fileName = imageName             let fileURL = documentsDirectory.appendingPathComponent(fileName)             guard let data = UIImageJPEGRepresentation(image, 1)  else { return }             //Checks if file exists, removes it if so.             if FileManager.default.fileExists(atPath: fileURL.path) {                 do {                     try FileManager.default.removeItem(atPath: fileURL.path)                     print("Removed old image")                 } catch let removeError {                     print("couldn't remove file at path", removeError)                 }             }             do {                 try data.write(to: fileURL)                 print(" NotificationService saveImage() : image saved")             } catch let error {                 print("NotificationService saveImage() :  saving file with error", error)             }         } 

didReceive :

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {                  print("NotificationService: dide receive called")                 self.contentHandler = contentHandler                 bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)                  if let bestAttemptContent = bestAttemptContent {                     if let urlString = bestAttemptContent.userInfo["attachment-url"] as? String,                         let data = NSData(contentsOf: URL(string:urlString)!) as Data? {                         let path = NSTemporaryDirectory() + "attachment"                          _ = FileManager.default.createFile(atPath: path, contents: data, attributes: nil)                          do {                             let file = URL(fileURLWithPath: path)                             let attachment = try UNNotificationAttachment(identifier: "attachment", url: file,options:[UNNotificationAttachmentOptionsTypeHintKey : "public.jpeg"])                               bestAttemptContent.attachments = [attachment]                          } catch {                             print(error)                          }                          //get the image and save it to disk for reuse                         let image = UIImage(data: data)                         saveImage(imageName: "promotionImage", image: image!)                       } // else {         //            //                if let contentHandler: ((UNNotificationContent) -> Void) =         //            //                    self.notificationContentHandler,         //            //                    let content: UNNotificationContent = self.notificationContent {         //            //                    contentHandler(content)  }
                                   contentHandler(bestAttemptContent)                 }              } 

Permisos de petición y respuesta WebSocket, socket io en Swift

soy nuevo en el desarrollo con swift y tengo un problema. he colocado en el info.plist la propiedad app transform security settings en allow arbitrary loads tengo entendido que sirve para permitir cualquier tipo de petición y respuesta. En socket io tengo el siguiente ejemplo de la documentación.

import SocketIO  let manager = SocketManager(socketURL: URL(string: "http://localhost:8080")!, config: [.log(true), .compress]) let socket = manager.defaultSocket socket.on(clientEvent: .connect) {(data, ack) in         print("socket connected")     }     let socketData = ["String": "serviceAlive"] as [String : Any]     socket.emit("user", socketData) socket.on("user") {data, ack in         print(data)      } socket.connect() 

En websocketswift tengo lo siguiente

let ws = WebSocket("ws://localhost:8080/Sockets-war/message")          ws.event.open = {             print("opened")         }         ws.event.close = { code, reason, clean in             print("close")         }         ws.event.error = { error in             print("error \(error)")         }         ws.event.message = { message in             if let text = message as? String {                 print("recv: \(text)")             }         } 

Pero en ambos casos solo consigo que en el servidor me muestre que ha sido conectado pero no emite y consume nada. Ambos casos WebSocket y socket io los he consumido con javascript y funciona perfectamente, solo en swift falla. utilizo swift 4.2, xcode 10, socket io 14.0.0 y de swiftweb 13.4.0

Send TCP Command using Swift

I need to be able to send a TCP/IP command to a projector using Swift on MacOS. I have found a number of different frameworks but haven’t had any luck either getting them to work or actually sending the command.

What is the best way to simply send a command? I know the IP address, the Port and the command to send. just need to know how