Swift Playground

RSS for tag

Learn and explore coding in Swift through interactive learning experiences on the Swift Playground app for iPadOS and macOS.

Posts under Swift Playground tag

92 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Beginner Question - Local SPM Folder Structure
Hi there, I am working on an iOS mobile app, with a MVVM architecture and created an SPM folders for my DesignSystem, CoreKit, UnityBridge, and VoicePipeline. I added the packages locally, and dragged them into the project. Is working this way recommended? Or not? Should all the SPM folders I listed above be used this way, or should only some? New to this, unsure what is best. I do plan on sharing my code with other devs to work on. I thought this made sense, but if i did it the other way I was unsure how I would share the packages what is a best practice. Thanks so much!
1
0
52
5d
Issue with #Playground and Foundation Model
Hi all, I’m encountering an issue when trying to run Apple Foundation Models in a blank project targeting iOS 26. Below are the details: Xcode: Latest version with iOS 26 SDK macOS: macOS 26 Tahoe (installed on main disk) Mac: 16” MacBook Pro with M2 Pro chip Apple Intelligence: Available and functional on this machine Problem: I created a new blank iOS project, set the deployment target to iOS 26, and ran the following minimal code using Foundation Models. However, I get no response at all in the output - not even an error. The app runs, but the model does not produce any output. #Playground { let session = LanguageModelSession() let response = try await session.respond(to: "Tell me a story") } Then, I tried to catch an error with this code: #Playground { let session = LanguageModelSession() do { let response = try await session.respond(to: "Tell me a story") print(response) } catch { print("Failed to get response:", error) } print("This line, never gets executed") } And got these results: I’ve done further testing and discovered something important: I tried running the Code Along sample project, and there the #Playground macro worked without issues. The only significant difference I noticed was the Canvas run destination: In my original project, I was using iPhone 16 Pro (iOS 26) as the run target in Canvas. Apple Intelligence was enabled on the simulator, but no response was returned when executing the prompt. In the sample project, the Canvas was running on My Mac. I attempted to match that setup, but at first, my destination was My Mac (Designed for iPad), which still didn’t work. The macro finally executed properly once I switched to My Mac (AppKit). So the question is ... it seems that for now, Foundation Models and the #Playground macro only run correctly when the canvas or destination is set to “My Mac (AppKit)”?
7
0
367
5d
Checking the contents of a TextField variable method not working
Hoping someone can help me with this… The error is… Generic parameter ‘/‘ cannot be inferred. .multilineTextAlignment(.center) .onAppear(perform: { var checkFirstCardLatitude = cards.firstCardLatitude let charArray = Array(checkFirstCardLatitude) let allowed: [Character] = ["-", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] for char in charArray { if char != allowed { cards.firstCardLatitude = "000.000000" // Reset Text Field } } })
26
0
281
May ’25
iPhone Doesn't Support App's Architectures (SwiftPM)
Hi, after recently upgrading Xcode to the latest version, I encountered a new bug that prevented me from building the app on my iPhone. Puzzlingly, the app still builds and runs fine on a simulator. Because I am working with a Swift Playground file, the option is not available to simply change the architecture setting. I found a similar setting within the Schemes, but after trying a combination of different architecture settings, the app still doesn't build properly. I noticed the BuildAction seemed to be changing, so I believe that the setting was properly affecting the Architecture setting. Even with a separate dummy test project (SwiftPM), I still ran into the same issues. I updated my iPhone OS to the latest version as well after initially encountering the bug. I'm wondering if anybody is running into the same issues, and if any solutions have been found.
3
0
83
Apr ’25
LLDB RPC server crash in Xcode 16.3
Created a new project in Xcode 16.3. While adding breakpoints app is crashing every time in Xcode and playground both. Tried with swift 5 and swift 6 getting same error. Crash reason : Couldn't find the Objective-C runtime library in loaded images. Message from debugger: The LLDB RPC server has crashed. You may need to manually terminate your process lldb-rpc-server-2025-04-14-092736.txt
4
6
267
May ’25
Issue with calculating the distance between two points on a map
I have an error issue that I haven’t been able to solve despite doing extensive research. In fact the similar examples I have found so far have been educational but I have not been able to make work. The example below I am hoping will be easy to fix as it is only producing errors with one line of code… import SwiftUI import CoreLocation var currentLon = Double() var currentLat = Double() extension CLLocation { class func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance { let from = CLLocation(latitude: from.latitude, longitude: from.longitude) let to = CLLocation(latitude: to.latitude, longitude: to.longitude) return from.distance(from: to) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { currentLon = (locations.last?.coordinate.longitude)! currentLat = (locations.last?.coordinate.latitude)! }/*⚠️ Not sure if this function will work? (Update User Location coordinates on the move?)*/ } struct Positions: Identifiable { let id = UUID() let name: String let latitude: Double let longitude: Double var coordinate: CLLocationCoordinate2D { CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } } struct GameMapView: View { let from = CLLocationCoordinate2D(latitude: currentLon, longitude: currentLat) let to = CLLocationCoordinate2D(latitude: thisCardPositionLongitude, longitude: thisCardPositionLongitude) let distanceFrom = from.distance(from: to) /*⚠️ ERRORS: 1. Cannot use instance member 'from' within property initializer; property initializers run before 'self' is available. 2. Cannot use instance member 'to' within property initializer; property initializers run before 'self' is available. 3. Value of type 'CLLocationCoordinate2D' has no member 'distance'. */ @State private var region = MKCoordinateRegion( center: CLLocationCoordinate2D( latitude: thisCardPositionLatitude, longitude: thisCardPositionLongitude), span: MKCoordinateSpan( latitudeDelta: 0.0001, longitudeDelta: 0.0001) ) var body: some View { Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: locations){ place in MapMarker(coordinate: place.coordinate,tint: Color.accentColor) } .edgesIgnoringSafeArea(.all) VStack { Print("Distance from Location: \(distanceFrom)") font(.largeTitle) padding() }
1
0
76
Apr ’25
Piece of code in Playground that reliably crashes lldb server
Dare anyone try the following code in any Playground: // Define a model that conforms to Codable struct User: Codable { var name: String var age: Int var email: String? } // JSON data (as a string for demonstration) let jsonString = """ { "name": "John Doe", "age": 30, "email": "john@example.com" } """ // Convert the JSON string to Data if let jsonData = jsonString.data(using: .utf8) { do { // Parse the JSON data into the User model let user = try JSONDecoder().decode(User.self, from: jsonData) print("Name: \(user.name), Age: \(user.age), Email: \(user.email ?? "N/A")") } catch { print("Error decoding JSON: \(error)") } } I tested with Xcode 16.2 and latest 16.3, it reliably crashes the lldb server!
6
1
154
Apr ’25
‘Keep going with apps’ Crash during Creature Add steps
Hello fellow Techies! I am currently doing the Swift Playgrounds “Keep Going with Apps” on my iPad Pro. Everything has been going as designed until I got to the ‘Add and Delete Creatures‘ module. The lesson concludes with being able to add a creature to your list in the CreatureZoo. When you run the app from the playground, you can fill out the fields and tap ‘Add’ and that is when the app dims and after 5 seconds I get the notification that the app has an unknown crash. I have reviewed the lessons leading up to it, but I can’t find anything wrong. (Full Disclosure: I really have no clue what I am looking at some of time.) Has anyone else ran into this? `import SwiftUI import Guide struct CreatureEditor: View { //#-learning-code-snippet(defineVariablesCreatureEditor) //#-learning-code-snippet(environmentValue) @State var newCreature : Creature = Creature(name: "", emoji: "") @EnvironmentObject var data : CreatureZoo @Environment(.dismiss) var dismiss var body: some View { SPCAssessableGroup(view: self) { VStack(alignment: .leading) { Form { Section("Name") { //#-learning-code-snippet(addACreatureEditorTextField) TextField("What is your monster's name?", text: $newCreature.name) } Section("Emoji") { TextField("What does your monster look like?", text: $newCreature.emoji) } Section("Creature Preview") { CreatureRow(creature: newCreature) } } } .toolbar { ToolbarItem { Button("Add") { data.creatures.append(newCreature) dismiss() } } } //#-learning-code-snippet(addButtonToToolbar) } } } struct CreatureEditor_Previews: PreviewProvider { static var previews: some View { NavigationStack() { CreatureEditor().environmentObject(CreatureZoo()) } } }’
4
0
183
Mar ’25
Swift Playground 4.6 - App Fails to Run with import AppIntent
Hi everyone, I’ve been developing an app using Swift Playgrounds, and it was working fine in version 4.5. However, after updating to Swift Playground 4.6, the app no longer runs. After some testing, I found that the issue occurs when import AppIntent is included. Here’s a simple example: import SwiftUI //import AppIntents // <- If this line is included, Preview and Run fail. @main struct MyApp: App { var body: some Scene { WindowGroup { Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) Text("Hello, world!") } } } Has anyone else encountered this issue? Thanks!
2
1
246
Mar ’25
Swift Playgrounds 4.6 removes support for libraries?
I had several library projects that were working in Swift Playgrounds < 4.6 but I get several duplicate compilation errors and previews will not build in Swift Playgrounds > 4.6. Does anyone know how to fix this issue? Example project: This project builds and runs fine under Swift Playgrounds 4.5.1 however it will not run complaining multiple commands produce generated output files under Swift Playgrounds 4.6.1, 4.6.2, and 4.6.3. https://github.com/kudit/Compatibility Download this repository and add the extension ".swiftpm" to the folder and double click to open in Swift Playgrounds. If running on earlier Swift Playgrounds you can see there are no errors and previews work great (on both macOS and iPadOS versions of Swift Playgrounds 4.5.x). However, on Swift Playgrounds 4.6.x, previews will not display. Are embedded libraries not support anymore? This would be very disappointing. I posted this as a Feedback weeks ago with no response: FB16509699
4
0
305
Jun ’25
PlaygroundSupport no longer available for Playground apps
In Swift Playground 4.6.2 the package PlaygroundSupport is no longer available to Playground apps. The following test previously permitted apps run in the Playground vs compiled in XCode to support different behavior: #if canImport(PlaygroundSupport) container = NSPersistentContainer(name: "myApp", managedObjectModel: Self.createModel()) #else container = NSPersistentCloudKitContainer(name: "myApp") #endif Since Swift Playground 4.6.2 the PlaygroundSupport package is no longer available for app projects in Playgrounds. Is there a different compile type test which can be used to differentiate compilation for Swift Playground apps ? I am currently having to use a runtime workaround (below) but would prefer a compile time test is an alternative is available. public static var inPlayground: Bool { if Bundle.allBundles.contains(where: { ($0.bundleIdentifier ?? "").contains("swift-playgrounds") }) { return true } else { return false } }
1
1
412
Feb ’25
Bundle Display Name Swift Playgrounds
I am attempting to use the AVSpeechSynthesizer to include text to speech in my Swift Playgrounds project, but when I attempt to use it on my IPhone i get the following errors: It works just fine on the simulator, but no audio is produced when I run it on-device. Is there a way to set this "bundle display name" within Swift Playgrounds, or are there any workarounds? My code: import AVFoundation class Speaker { let synthesizer = AVSpeechSynthesizer() func speak() { let utterance = AVSpeechUtterance(string: "Test, I am the speaker") synthesizer.speak(utterance) } }
1
1
345
Feb ’25
Playground app on MacOS
Hi! I have a concern for the SSC: I worked on the Playground app, but on MacOS. My app has been developped to be firstly used on a mac, as the playground app let you directly download your app on you mac and act as a real one. When i wanted to submit, I noticed there is nowhere to specify whether your app should be tested on iPad or on MacBook. I saw Playground apps would be tested on an iPad, does it mean I have to refactor my app to work on one, or i can mention on a comment that it is a MacOS app, and should therefore be tested on a mac? Thanks for your help on this
1
0
442
Feb ’25
Regarding AR App Submission Built in Xcode - Swift Student Challenge submission
Hello guys, I have a question regarding the submission requirements. My app uses ARKit and requires Metal files for shaders, which are not supported by Swift Playgrounds. Therefore, I developed my app using Xcode. (swift playgrounds returning error for metal file) Since my app relies on a real device for proper functionality, I would like to know if, under these circumstances, the scene build is performed by Xcode. If the build were instead done by Swift Playgrounds, my scene would not function correctly. I'm asking that because of this note Thank you for your time and assistance.
1
0
453
Feb ’25
Metal not working in Swift Playgrounds (SSC Scene)
Hi everyone, I'm currently working on a Swift Playgrounds project where I need to incorporate a Metal shader file. However, when I tried to include my shader file (PincushionShader.metal), I encountered the following error: Is it possible to use Metal shader files within Swift Playgrounds, it is really important for my swift student challenge scene? If not, are there any workarounds or recommended approaches for testing Metal shaders in a similar environment? Any guidance or suggestions would be greatly appreciated!
3
0
533
Feb ’25
Swift student challenge assessment query!!!
I was just filling the submission for the swift student challenge and there is a note below adding the zip file saying Note: Xcode app playgrounds are run in Simulator. Now my xcode app playground(.swiftpm) is an AR app and needs an ipad or an iphone to run . So will my submission still be eligible for assessment and checked on ipad???
1
0
581
Feb ’25
Xcode: Skipping Duplicate Build File in Compile Sources in a .swiftpm Project – How to Fix?
I'm trying to add Assets.xcassets to a .swiftpm project, but I'm getting the warning: ⚠️ Ignoring duplicate build file in build source build phase (Just to know, that is about developing in XCODE, in Swift Playgrounds does not appear it, even in this second being harder to setting up) The problem is that there are no “Build Phases” in XCODE to remove duplicate files manually. I've already tried adding the path of Assets.xcassets in the resources property of Package.swift, like: .executableTarget( name: "AppModule", path: ".", resources: [ .process("Assets.xcassets") ] ) Even so, the warning persists. Does anyone know how to solve this? Is there any way to remove duplicate references or force a cleanup of the Swift Package Manager cache to fix it? I appreciate any tips! 🙏🚀
2
2
497
Feb ’25
Question about how to access to camera on Swift Playground
When I was working on my project for Swift Student Challenge, I found an interesting fact regarding camera access. If I create an App project on Xcode, the camera capture works well on it. However, if I copied and pasted the code on an App Playground project on Xcode, it crashed and output several errors. I am wondering why this is happening.
1
0
419
Feb ’25