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

Swift Documentation

Posts under Swift tag

2,017 Posts
Sort by:
Post not yet marked as solved
0 Replies
27 Views
In larger scenes, I need to record motion trajectories. RoomCaptureSession always starts from (0,0,0), and I use the last tracked point as the offset value to connect multiple trajectory points, just like StructureBuilder merging models But when StructureBuilder merged, it eliminated some of the models, which would make the trajectory points I saved lose accuracy, and I cannot know how much scene size was specifically eliminated between them Is there any way you can help me?
Posted
by
Post not yet marked as solved
0 Replies
69 Views
Hello everyone My goal is to create Apple's activity ring sparkle effect. So I found Paul Hudson's Vortex library. There is already a sparkle effect, but I don't know how to modify it to achieve my goal. Because I'm pretty new to SwiftUI animations. Does anyone have any idea how I could do this? Vortex project: https://github.com/twostraws/Vortex
Posted
by
Post not yet marked as solved
3 Replies
89 Views
I'm defining a typealias for a set, and then creating an extension for the new typealias. When I do this, I'm getting an odd syntax error. Any/all guidance appreciated. typealias IntSet = Set<Int> extension IntSet { func aFunction() -> Set<String> { let array: [String] = self.map { "\($0)" } return Set(array) } } At the return line, I get the following syntax error: Cannot convert return expression of type 'Set<Int>' to return type 'Set<String>' Even if I replace the return line with the following, I get the same compile error return Set("array")
Posted
by
Post not yet marked as solved
1 Replies
66 Views
Hi everyone, I’m just starting with swift and Xcode and have a basic question. I have the following code I found online for an app that generates math addition questions. I would like to run this Math app on my iPhone just before I open the apps I use most often (let’s say mail, WhatsApp, calendar and notes) ask me a maths question and if I answer correctly, carryon with the app originally intended to be opened. I can do the opening of the Math app before the apps I use more often with shortcuts. I would like to modify the code bellow so that if I answer correctly it “closes” itself and returns to the originally intended app. With that intention I included the “exit(0)”, but I get an error. Thanks for your help in advance! Best, Tom struct ContentView: View { @State private var correctAnswer = 0 @State private var choiceArray : [Int] = [0, 1, 2, 3] @State private var firstNumber = 0 @State private var secondNumber = 0 @State private var difficulty = 1000 var body: some View { VStack { Text("(firstNumber) + (secondNumber)") .font(.largeTitle) .bold() HStack { ForEach(0..<2) {index in Button { answerIsCorrect(answer: choiceArray[index]) generateAnswers() } label: { AnswerButton(number: choiceArray[index]) } } } HStack { ForEach(2..<4) {index in Button { answerIsCorrect(answer: choiceArray[index]) generateAnswers() } label: { AnswerButton(number: choiceArray[index]) } } } } func answerIsCorrect(answer: Int){ if answer == correctAnswer {exit(0)} } } func generateAnswers(){ firstNumber = Int.random(in: 0...(difficulty/2)) secondNumber = Int.random(in: 0...(difficulty/2)) var answerList = Int correctAnswer = firstNumber + secondNumber for _ in 0...2 { answerList.append(Int.random(in: 0...difficulty)) } answerList.append(correctAnswer) choiceArray = answerList.shuffled() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Posted
by
Post not yet marked as solved
0 Replies
63 Views
I'd like to know how to test behavior in Swift on Desktop that needs to interact with external elements, in my case the Finder. My goal is simple: add an option in the right-click menu of the Finder that will open my application with the selected entry or entries (file or folder) from the Finder. I have thus set the elements NSMenuItem, NSMessage, NSPortName, NSRequiredContext (NSApplicationIdentifier: com.apple.finder) etc. I also created a class FinderService with a function performService having this declaration: func performService(_ pboard: NSPasteboard, userData: String, error: AutoreleasingUnsafeMutablePointer&lt;NSString&gt;) { NSLog("performService called!") } And I instantiated my class like this: NSApplication.shared.servicesProvider = FinderService(). However, when I build and launch the application nothing happens, well my application runs fine and the instantiation of the class seems to be correctly called. But when I open my Finder, my action is not displayed in the right-click context menu. And in the logs of my application, no error appears. How can I test this?
Posted
by
Post not yet marked as solved
0 Replies
50 Views
Hi Team Is there a way to extract a colorized scan as well with using the roomplan SDK ? . If yes, can you point me to the right reference link ? Does the roomplan SDK provide dimensions of the room ?
Posted
by
Post not yet marked as solved
1 Replies
100 Views
For calling swift api of a class to cpp , we need to include SwiftInterfaceGeneratedHeader to cpp file and then we can access swift class api in cpp . Signature of swift class with public apis will be added to the SwiftInterfaceGeneratedHeader. We find an odd behaviour here . Signature of classes will be added to SwiftInterfaceGeneratedHeader in alphabetical order (swift class name alphabetically lower will be added first to generated header). If we have a swift class which is referenced by another swift class Api , then referenced class's name should be alphabetically lower that referee class , otherwise we will get a build error :- "Unknown class name". public class A { public func funca () { print ("class A") } } public class B { public func funcb () { print ("class B") } public func funcb2 (pA:A) { pA.funca() } public func funcb3 (pC:C) { pC.funcc() } } public class C { public func funcc () { print ("class C") } } Cpp class where we include bridging header after turning on swift cpp interop : class Test1 { public: static void testfunc (); }; #include "Test1.hpp" #include "cppswiftinterop-Swift.h" void Test1::testfunc() { } Here , we have three swift classes , Class A,B,C. And since we are including SwiftInterfaceGeneratedHeader in cpp , signature of these class will be added to the generated header . In this project , we are referencing Class A and Class C from Class B . And since A is alphabetically lower that B , it works fine (because signature of A in Generated header will be added before it is referenced by B). But since C is alphabetically above than B , it will through build error (Unknown type name 'C') , because Signature of C in Generated header will be added after it is referenced by class B). If i rename Class C to Class AA then , it works fine. Is this a bug in swift cpp interop?
Posted
by
Post not yet marked as solved
1 Replies
48 Views
Hello everyone, I have a problem in a project I am currently working on. Some background information regarding the problem is that I am creating some buttons in a foreach loop in another script that retrieve information from a server. These buttons are displayed in a grid with a width of 2 entries. The element that the buttons belong to also contain a fullScreenCover functionality, but the full screen cover functionality is only being called for the top four entries in the grid but the button works on all of the entries. Here is the partial code: Button(action:{ let _ = print("Button was clicked",self.title) isDetailPresented.toggle() let _ = print("Button was clicked",self.isDetailPresented) }) { VStack { ... } .foregroundColor(Color.black) .fullScreenCover(isPresented: $isDetailPresented, onDismiss: { //some function is being called here let _ = print("Moving on") }, content: { let _ = print("I have moved on") //a view to be opened }) I already checked that the boolean changes on all entries but I can't figure out why the content is not being displayed for the entries below the 4 top ones. Any help would be appreciated.
Posted
by
Post not yet marked as solved
0 Replies
90 Views
Hello, technical friends, I am developing a custom keyboard extension, currently encountered a technical difficulty, almost asked AI and Google have not solved my problem. 

 Problem description: 
 When my App was first installed, I opened Settings from the App, enabled full access, and crashed when I returned to the App. Run the App for the second time, open the Settings from the App, update the full access permission, and automatically re-run the App after returning to the App, and then the third, fourth, and NTH times will not crash. 

 Seems like ios will kill host apps for custom keyboard extensions after full access is updated? I want my App installed for the first time to update full access to return App without crashing, but don't know how to fix this problem. I look forward to the technical experts working in Apple development to help me provide relevant technical methods and ideas so that I can solve this problem. Thank you very much! When tracing debugging in xcode, after the App forces exit, the console prompts: Message from debugger: Terminated due to signal 9 When I was monitoring CPU and memory usage, it was very low and I didn't see anything unusual.
Posted
by
Post not yet marked as solved
3 Replies
93 Views
Im making an API call using notions API to access and retrieve data from my Notion page and I'm successfully making the url request and accessing the page, however I seem to be struggling with returning the actual data that I have in that page and parsing the JSON data as right now, my console only outputs the makeup of my notion page rather than the formatted and parsed data. I made a codable struct meant to replicate the structure of a notion page based off their documentation then I'm passing that struct to my JSON parsing function but my data still is not being parsed and returned. heres what I have. import Foundation struct Page: Codable, Hashable { //Codable struct for notion "Page" for defining content aswell as object representation in a codable struct of all the basic components that make up a notion page per notion's documentation let created_time: String let created_by: String let last_edited_time: String let object: String let cover: String let emoji: String let icon: String struct properties: Codable, Hashable { let title: String let dueDate: String let status: String } struct dueDate: Codable, Hashable { let id: String let type: String let date: String let start: String let end: String? //optionals added to "end" and "time_zone" as these values are set to null in the documentation let time_zone: String? } struct Title: Codable,Hashable { let id: String let type: String let title: [String] } struct annotations: Codable, Hashable { let bold: Bool let italic: Bool let strikethrough: Bool let underline: Bool let code: Bool let color: String } let English: String let Korean: String let Pronounciation: String let in_trash: Bool let public_url: String? let annotations: Bool } let url = URL(string: "https://api.notion.com/v1/pages/8efc0ca3d9cc44fbb1f34383b794b817") let apiKey = "secret_Olc3LXnpDW6gI8o0Eu11lQr2krU4b870ryjFPJGCZs4" let session = URLSession.shared func makeRequest() { if let url = url { var request = URLRequest(url: url) let header = "Bearer " + apiKey //authorization header declaration request.addValue(header, forHTTPHeaderField: "authorization") //append apikey request.addValue("2022-06-28",forHTTPHeaderField: "Notion-Version") //specify version per notions requirments let task = URLSession.shared.dataTask(with: request) { data, response, error in if let httpError = error { print("could not establish HTTP connection:\(httpError)") } else { if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { } else { print("invalid api key:\(httpResponse.statusCode)") } } } if let unwrapData = data { //safely unwrapping the data value using if let if let makeString = String(data: unwrapData, encoding: .utf8) { print(makeString) } else { print("no data is being returned:") } do { let decoder = JSONDecoder() //JSONDecoder method to decode api data, let codeUnwrappedData = try decoder.decode(Page.self,from: unwrapData) //Page. specifies its a struct, from: passes the data parmeter that contains the api data to be decoded //PASS STRUCTURESDATABASE STRUCT print("data:\(codeUnwrappedData)") } catch { print("could not parse json data") } if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { print(String(data: unwrapData, encoding: .utf8)!) } else { print("unsuccessful http response:\(httpResponse)") } } } } task.resume() } }
Posted
by
Post not yet marked as solved
2 Replies
82 Views
Hi everyone i am having trouble with layout. I am using storyboard for UI. While most of the iphone version are ok with my auto layout ... the first generation Iphone SE is giving me errors. To publish app on app store do i need it to be working perfectly on first generation Iphone SE too ? Any link or knowledge on layout for story board is much appreciated.
Posted
by
Post not yet marked as solved
0 Replies
58 Views
When I try to share a image of a component using the ImageRenderer, the type is not .png while sharing the image created using ShareLink (The type is .jpeg for some reasons...) My code looks like this: ShareLink( "Share", item: ( ImageRenderer( content: shareView.frame( width: 420, height: 520 ) ).uiImage?.pngData() )!, preview: SharePreview( "Share Preview", image: ( ImageRenderer( content: shareView.frame( width: 420, height: 520 ) ).uiImage?.pngData() )! ) ) Also the image shared is always in low resolution, if anyone knows what to do in this case let me know! Any helps will be appreciated!
Posted
by
Post marked as solved
1 Replies
96 Views
I'm getting an "No exact matches in call to instance method 'setValue'" error for a property that has a enum as a value. How do I fix this? Any help would be appreciated. enum FluidUnit: CaseIterable, Identifiable { case ounce, liter var id: Self { self } var title: String { switch self { case .ounce: return "ounce" case .liter: return "liters" } } } @Model class Drink: Identifiable, Hashable { let id: UUID = UUID() let name: String = "" var shortName: String = "" var amount: Double = 0.0 let unitOfMeasure: FluidUnit = FluidUnit.ounce let date: Date = Date() var image: String = "water" var favorite: Bool = false init(name: String, amount: Double, unitOfMeasure: FluidUnit, image: String, favorite: Bool = false, shortName: String = "") { self.id = UUID() self.name = name self.amount = amount self.unitOfMeasure = unitOfMeasure self.date = Date() self.image = image self.favorite = favorite self.shortName = shortName } static func == (lhs: Drink, rhs: Drink) -> Bool { lhs.id == rhs.id } func hash(into hasher: inout Hasher) { hasher.combine(id) } }
Posted
by
Post not yet marked as solved
0 Replies
85 Views
[visionOS Question] I’m using the hierarchy of an entity loaded from a RealityKit Pro project to drive the content of a NavigationSplitView. I’d like to render any of the child entities in a RealityKitView in the detail pane when a user selects the child entity name from the list in the NavigationSplitView. I haven’t been able to render the entity in the detail view yet. I have tried updating the position/scaling to no avail. I also tried adding an AnchorEntity and set the child entity parent to it. I’m starting to suspect that the way to do it is to create a scene for each individual child entity in the RealityKit Pro project. I’d prefer to avoid this approach as I want a data-driven approach. Is there a way to implement my idea in RealityKit in code?
Posted
by
Post not yet marked as solved
1 Replies
94 Views
Hi, Looking for some guidance on getting my code approved through app connect. Based on the crash logs, it appears the application is experiencing crashes related to an EXC_CRASH (SIGABRT), which is typically triggered by the app receiving an abort signal, often as a result of an unhandled exception or other critical errors that cause the app to terminate abruptly. Any ideas on how to resolve?
Posted
by
Post not yet marked as solved
1 Replies
76 Views
I used a custom time format in the DateTimePicker, such as 'hh:mm a' for 12-hour format. Although the device's time format is set to 24-hour mode, my sample app displays time in 24-hour format like '23:10' instead of the desired 12-hour format like '11:10 PM'. I've already set the locale for the 12-hour format. Has anyone else encountered this issue, and what could be the solution?
Posted
by
Post not yet marked as solved
0 Replies
57 Views
Is it possible to link CBPeripheral which comes from scan delegate with the peripheral which comes from retrieveConnectedPeripherals result ? My assumption is that is not fully possible, but I want to confirm. They don't have nothing in common, except the name. But in my use case I have products which don't have name.
Posted
by
Post not yet marked as solved
0 Replies
47 Views
The app downloads assets consisting of custom fonts using tags from On-Demand Resources, registers them in the system font, and provides them to other apps such as Freeform through UIFontPickerViewController. Custom Fonts that were applied well until iOS 16 appear as Helvetica starting from iOS 17 and cannot be used. As the font list appears in the device's Settings > General > Font, the font downloaded from On-Demand Resources is registered in the system font. It has been confirmed to occur particularly frequently starting from iPhone 15 and iOS 17 and above. The app requests download from On-Demand Resources with NSBundleResourceRequest along with tags, receives assets in response with conditionally beginAccessingResources and beginAccessingResources, and then registers them in the system using CTFontManagerRegisterFontURLs.
Posted
by
Post not yet marked as solved
0 Replies
94 Views
On versions iOS 14+, my app which is connected by bluetooth to another device will become slow to write information. This isn't a couple hundred ms or a second or two, but upwards of 10 minutes for it to be sent and then 400 ms to be processed by the device and send its response back. I've confirmed with PacketLogger and with system logs that what commands we are sending with .writeValue are taking over 10 minutes. This is the timestamp of when we are writing to the device This is the PacketLogger timestamp of when the phone actually wrote to our device This doesn't occur immediately, but is intermittent and once it does begin to occur, there's nothing to do to get out of it except for connecting once again to the device. Which, overtime, the issue begins to spring up again. So why is it taking 13 minutes for it to go through the phone and finally being sent?
Posted
by