Swift

Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Swift Documentation

Posts under Swift tag

2,413 results found
Post marked as solved
152 Views

Reduce/replace loops in my conditional checks ? [CoreData]

I am looking to integrate my code with CoreData. Presently I have the following of which allows a worker to check their requirements against an advert e.g. if the worker needs x3 sponges to clean a bathroom, then the advert must provide those sponges, but the worker can only work on set days: var cdExample: [CleaningRota] = [bathroomMonday, kitchenFriday]&#9;// [Full sample code](https://developer.apple.com/forums/content/attachment/648c2166-46f3-44a3-bfc7-5e36f3d38721){: .log-attachment} CORE DATA EXAMPLE &#9;&#9;let personAvailable: [Person] = [kath, mavis] &#9;&#9;//CORE DATA EXAMPLE : WORK ON OFFER &#9;&#9;for work in cdExample { &#9;&#9;&#9;&#9;//WORK TOOLS PROVIDED ON SITE &#9;&#9;&#9;&#9;for toolsAvailable in work.tool { &#9;&#9;&#9;&#9;&#9;&#9;//PERSONS AVAILABLE TO WORK &#9;&#9;&#9;&#9;&#9;&#9;for person in personAvailable { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;//PERSONAL REQUEST : SPECIFIC WORK DAY &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;if person.avilability == work.day { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;//CHECK PERSON TOOL REQUIREMENTS FOR JOB &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;for personRequirement in person.materialsNeeded { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;//CYCLE THROUGH TOOLS WORKER NEEDS ON SITE &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;if personRequirement.tool == toolsAvailable.name { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;//CONFIRM TOOLS WORKER NEEDS ARE FULLY PROVIDED &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;//AVOID CHECKING SAME STOCK TWICE IF CONDITION PREVIOUSLY MET &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;if personRequirement.quantity <= toolsAvailable.stock && personRequirement.met == false { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;print(">>0> \(person.name)") &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;print(">>1> \(personRequirement.tool) : \(personRequirement.quantity)") &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;print(">>2> \(toolsAvailable.name) : \(toolsAvailable.stock)") &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;personRequirement.met = true &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;person.materialID.append(toolsAvailable.id) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;} &#9;&#9;} As the adverts and requirements pile up this kind of system will not scale very quickly. I would like to know if there is a better way to model this data, or to check conditions. I plan to pull the cdExample from CoreData, and am unfamiliar with using it. Being a proprietary Apple Framework I do not know if anyone will help me here, but if not then how best to achieve what I want without a pyramid of doom (which I don't mind), is there a better way please? I also need to remove the stock, which I ran into trouble with as I had too many loops and hit a bug in Xcode, so I think I'm doing something wrong with all of these loops ?
Asked
by forklift.
Last updated .
Post marked as solved
124 Views

Generic JSON response from API request

Hello guys. I've been stuck two days with this issue, hope you can understand my question below because I'm still new with Swift. I want to create a generic function that request some JSON data from an API, decode the response using the Codable protocol and save it in a @State variable to update the View Here is what I've done so far. struct Response: Codable {     var results: [Result] } struct Result: Codable {     var trackId: Int     var trackName: String     var collectionName: String } Here is the function     func loadData<T: Decodable>(model: T.Type) {         guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {             print("Invalid URL")             return         }         let request = URLRequest(url: url)         URLSession.shared.dataTask(with: request) { data, response, error in             if let data = data {                 if let decodedResponse = try? JSONDecoder().decode(model, from: data) {                     DispatchQueue.main.async {                         print(decodedResponse)                     }                     return                 }             }             print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")         }         .resume()     } The thing is, so far I'm only able to print the response, but I can't do something like this: DispatchQueue.main.async { self.results = decodedResponse.results } Because it shows me this error Value of type 'T' has no member ' results' Here is the View struct TestView: View {     @State private var results = [Result]()     var body: some View {         List(results, id: \.trackId) { item in             VStack(alignment: .leading) {                 Text(item.trackName)                     .font(.headline)                 Text(item.collectionName)             }         }         .onAppear {             loadData(model: Response.self)         }     } // Here is the function defined } Somebody could give a hint? I really appreciate it Thank you. Dennis
Asked
by DennisCM.
Last updated .
Post marked as unsolved
47 Views

Modal view using HalfModal creates a new tab in TabView

I have just fixed an issue where its solution was to move my code to different .swift files and then reference them as views in ContentView.swift. I have modal views in my new view swift files, using this repo - https://github.com/ViktorMaric/HalfModal, and now my Modal views show up as their own tab in my TabView, whereas they didn't before. My code is below... ContentView.swift - https://developer.apple.com/forums/content/attachment/80e41ced-67a1-4083-8bbb-49d1e9caa610 rocketView.swift - https://developer.apple.com/forums/content/attachment/00da3f2e-0be2-4ec9-8eb5-c7131****48d aboutView.swift - https://developer.apple.com/forums/content/attachment/e7e9d046-7637-48c0-aee5-8bb4fc43a278 launchesView.swift - https://developer.apple.com/forums/content/attachment/673078c5-6506-42ee-a150-f0f0db625afc
Asked
Last updated .
Post marked as solved
169 Views

How do I stop 'The compiler is unable to type-check this expression in reasonable time'

I am trying to write my first app, after adding another item to tab view, I get the error The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions How do I stop this error? my code is: my code - https://developer.apple.com/forums/content/attachment/30e42482-cc67-416a-b859-861c81bac7ff
Asked
Last updated .
Post marked as unsolved
53 Views

Why don't work URLSession in Swift Widget

I create widget with temperature from my site. In standart program all work, but in Widget on result i see "0" (info from var) Here code with mistake (DataProvider.swift) import Foundation class DataProvider { &#9;&#9; &#9;&#9;struct CurrencyJSON: Codable { &#9;&#9;&#9;&#9;var temp : String &#9;&#9;} &#9;&#9;static func getTemp() -> String { &#9;&#9;&#9;&#9; &#9;&#9;var dig : String = "0" &#9;&#9;print ("1") &#9;&#9;//on url this data: {temp:3.5}, this is my site, i can do anything format, may be make format: 3.5 (no json)? &#9;&#9;URLSession.shared.dataTask(with: URL(string: "http://example.com/weather.php")! ) {(data, response, error) in &#9;&#9;&#9;&#9;guard let data = data else { return } &#9;&#9;&#9;&#9;do { &#9;&#9;&#9;&#9;&#9;&#9;let res = try JSONDecoder().decode(CurrencyJSON.self, from: data) &#9;&#9;&#9;&#9;&#9;&#9;dig=res.temp &#9;&#9;&#9;&#9;&#9;&#9;print ("\(dig)") &#9;&#9;&#9;&#9;} catch let error { &#9;&#9;&#9;&#9;&#9;&#9;print("\(error)") &#9;&#9;&#9;&#9;} &#9;&#9;}.resume() &#9;&#9;return dig &#9;&#9;} &#9;&#9; } And on widget i see "0" (From this: var dig : String = "0"), why? Where i make mistake? Here my struct Provider: TimelineProvider: struct Provider: TimelineProvider { &#9;&#9;func placeholder(in context: Context) -> SimpleEntry { &#9;&#9;&#9;&#9;SimpleEntry(date: Date(), myString: "...") &#9;&#9;} &#9;&#9;func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) { &#9;&#9;&#9;&#9;let entry = SimpleEntry(date: Date(), myString: "...") &#9;&#9;&#9;&#9;completion(entry) &#9;&#9;} &#9;&#9;func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) { &#9;&#9;&#9;&#9;var entries: [SimpleEntry] = [] &#9;&#9;&#9;&#9;print ("1") &#9;&#9;&#9;&#9;// Generate a timeline consisting of five entries an hour apart, starting from the current date. &#9;&#9;&#9;&#9;let currentDate = Date() &#9;&#9;&#9;&#9;for hourOffset in 0 ..< 5 { &#9;&#9;&#9;&#9;&#9;&#9;let entryDate = Calendar.current.date(byAdding: .second, value: hourOffset * 10, to: currentDate)! &#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;let entry = SimpleEntry(date: entryDate, myString: DataProvider.getTemp()) &#9;&#9;&#9;&#9;&#9;&#9;entries.append(entry) &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;let timeline = Timeline(entries: entries, policy: .atEnd) &#9;&#9;&#9;&#9;completion(timeline) &#9;&#9;} }
Asked
by DenisVa.
Last updated .
Post marked as unsolved
36 Views

libswiftUIKit.dylib file error when i upload to Apple connect

Hi! I am trying to publish a new version of my app which is build with Xamarin and i get this error: ITMS-90433 Invalid Swift Support, The file libswiftUIKit.dylib doesn't have the correct code signature. What can i do to submit my app build because i have tried to copy the .dylib file from my application files such as Framework folder inside my app archive or even from XCode's Swift folder, but it's not working.  If I don’t create the SwiftSupport folder and copy the libswiftUIKit.dylib file from another location, I get this error: ITMS-90424 Invalid Swift Support - The SwiftSupport folder is empty. It says that I should rebuild my app using the current GM version of Xcode but I can not build my app using XCode because I’m working with Xamarin so I have to use Visual Studio to build and to archive it for publishing.  When I build my app using Visual Studio it doesn’t generate the SwiftSupport folder and the files inside it.  Does anybody know how to solve this because i have tried almost everything that i read on internet. Thank you in advance!
Asked
by MeriSS.
Last updated .
Post marked as unsolved
38 Views

Cannot find 'application' in scope

i get 2 of these errors ""Cannot find 'application' in scope"" what am i doing wrong or why is it not in scope? // // ViewController.swift // Diabell App // // Created by Richard Klug on 23/04/2021. // import UIKit import MessageUI class ViewController: UIViewController, MFMailComposeViewControllerDelegate {  override func viewDidLoad() {   super.viewDidLoad()   // Do any additional setup after loading the view.  }     //Function Email Bottom Left     @IBAction func Mail(_ sender: Any) {   showMailComposer()  }     func showMailComposer() {    guard MFMailComposeViewController.canSendMail() else{     return    }    let composer = MFMailComposeViewController()    composer.mailComposeDelegate = self    composer.setToRecipients(["richard.klug@diabell.se"])    composer.setSubject("Diabell App Help")    composer.setMessageBody("Fyll i vad du behöver hjälp med", isHTML: false)    present(composer, animated: true)  }      //Funktion Call Bottom Right       @IBAction func btnCallClick(_ sender: UIButton) {     if let phoneURL = URL(string: "tel://+46706106310"){       if application.canOpenUrl(phoneURL){         application.open(phoneURL, [:], completionHandler: nil)       }else{       }   }    } }
Asked
Last updated .
Post marked as solved
33 Views

What does 'Extra arguments at positions in call' mean?

I have a string - "productRaw" which I am splitting up to show in separate sectionData cells, whilst under the same "Item 1" cellData table view. This is the code I am using to split up the String and add each separate part to a separate sectionData cell. let group_array = document["product"] as? [String] ?? [""] let productName1 = group_array.first ?? "No data to display :(" let productRaw = "\(productName1)" let componentsRaw = productRaw.components(separatedBy: ", ") var product = [String: String]() for component in componentsRaw { let keyVal = component.components(separatedBy: ": ") product[keyVal[0]] = keyVal[1] } if let productName = product["Product Name"], let listingPrice = product["Listing Price"], let briefDescription = product["A brief description"], let productURL = product["Product URL"], let activeUntil = product["Listing active until"] { self.tableViewData = [cellData(opened: false, title: "Item 1", sectionData: [productName], [listingPrice], [briefDescription], [productURL], [activeUntil])] } Where I am declaring the individual cells I want to be shown for the first section - "Item 1", when I only use [productName] in my sectionData then this compiles without any issues. However when I also add , [listingPrice], [briefDescription], [productURL], [activeUntil] to my sectionData I receive the following error for the [cellData(opened: syntax. Extra arguments at positions #4, #5, #6, #7 in call So my question is, why am I receiving the above error and what can I do to resolve it?
Asked
Last updated .
Post marked as solved
107 Views

Assistant not opening the correct swift file

I am trying to open the swift file so that I can Ctrl + Drag from the image cell into the swift file that I generated. The file was generated by New File - Cocao Touch class, previously. With the main.storyboard open and then choosing Assistant, I get the ViewController.h for the scene I am in and not the ExploreCell.swift file that I have just generated. The book I am following as I am a beginner, says that I should set the file as automatic but I can't seem to be able to do that. What am I doing wrong?
Asked
by Rocky48.
Last updated .
Post marked as unsolved
756 Views

How to make a phone call with a button

Hi, how do I make a button so that when it is pressed, it calls a phone number?
Asked
Last updated .
Post marked as unsolved
27 Views

Unicode values in cookie makes cookies corrupted in WKWebView

Unicode values in cookies creating issue while loading the page url inside the iOS application. Web view is failing every time while reading the cookies and return my web page to login screen. Flow of app: We are using Chinese characters in the user name. Once we launch the url in native app webpage, cookies contains the username with it as provided, but it converted to unicode which makes cookies corrupted. Can anyone help me on this? Thanks in advance. Manoj
Asked
Last updated .
Post marked as solved
72 Views

how to resolve Cannot find 'XXXX' in scope

Hi im new at developing and i got 2 errors i can't seem to find an answer on google. here is my code and the errors are Cannot find 'self' in scope Cannot find 'present' in scope // // ViewController.swift // Diabell // // Created by Richard Klug on 14/04/2021. // import UIKit import MessageUI class ViewController: UIViewController {   override func viewDidLoad() {     super.viewDidLoad()     // Do any additional setup after loading the view.   }       @IBAction func emailbButtonTapped( sender: Any) {    showMailComposer()   } }   func showMailComposer() {     guard MFMailComposeViewController.canSendMail() else{       return     }     let composer = MFMailComposeViewController()     composer.mailComposeDelegate = self     composer.setToRecipients(["richard.klug@diabell.se"])     composer.setSubject("Diabell App Help")     composer.setMessageBody("Fyll i vad du behöver hjälp med", isHTML: false)     present(composer, animated: true)       }   extension ViewController: MFMailComposeViewControllerDelegate {     func mailComposeController( controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {       if let _ = error {         controller.dismiss(animated: true)         return       }       switch result {       case .cancelled:         print ("Cancelled")       case .failed:         print ("Failed to send")       case .saved:         print ("Saved")       case .sent:         print ("Email Sent")       }       controller.dismiss(animated: true)     } }
Asked
Last updated .
Post marked as unsolved
98 Views

Need help with Swift 4.2

Hi, I have started learning Swift recently and due to system specifications, I am learning how to build apps for iOS 12. I have written a code to update UI based on user's click. Note : This function is called in the IBAction Function     //Here i is a global variable     scoreLabel.text = "Score : \(score)"           progressLabel.text = "Question: \(questionNumber+1) / 13"           progressBar.frame.size.width = (CGFloat(view.frame.size.width) / 13) * CGFloat(i)     print("i: \(i)")     i = i + 1       //CGFloat(allQuestion.list.count) * CGFloat(questionNumber + 1)     print(progressBar.frame.size.width)  } But the progress bar frame is not getting updated. I checked and the value is getting updated but when I check on simulator, the progress bar is not updating, rest all are fine. Kindly help me out to solve this issue
Asked
Last updated .
Post marked as unsolved
22 Views

NavigationView bug in SwiftUI and iOS 13.0, 13.1

Hi everyone I am developing app on SwiftUI and I faced a very strange issue which I guess some of you might have already faced. So I have my View with custom Navigation system, and it works fine on every single iOS starting 13.2 but if I run my app on simulator 13.0 or 13.1, it shows blank screen everywhere I use navigation. What is even more interesting, if I add NavigationView {} to the top of the content of my view, the content starts to show but with the blank space at the top (I literally use two navigations on one screen) My question is have anyone already faced similar problems? Is there any solution or this is just a bug of simulator or something? I cannot test on a real device since all of them are running iOS 14 and later and I cannot find an iOS 13 device anywhere. Please help me someone
Asked
Last updated .
Post marked as unsolved
15 Views

How to upgrade the firmware of MFI devices?

At this moment I need to make an APP that can upgrade MFI devices. I can use EAaccessoy to communicate between devices and send and receive devices. How should I upgrade it? I try to use Mcumgr's Framework, but because the library is for BLE devices The library is of no use to me? Is there a library that can be used to upgrade the MFI device for reference? I use the IAP2 communication protocol.
Asked
by DashineJW.
Last updated .