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

91 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Xcode playground export is doesn't work
I am having issues with exported playgrounds from Xcode, when I try to open my exported swift fill I get the following message: "Couldn't load settings from contents.xcplayground" Xcode Version: Version 16.2 (16C5032a) Steps to reproduce Create new playground in Xcode. File->Export Open exported file. The issue still press persist after reinstalling Xcode.
0
0
158
Jan ’25
indices(where:) Swift Playgrounds Issue: "Cannot call value of non-function type Range<Int>"
Hey there- I'm having a quite interesting bug on Swift Playgrounds. I am trying to run my app with this following code snippet which does not compile on Swift Playgrounds, yet compiles on XCode (note: this is a Swift Playground app) if #available(iOS 18.0, *) { //simple function to get the indices of other items that have the same date as the "date" variable let indices = data!.indices(where: { item in let sameMonth = Calendar.current.component(.month, from: item.time) == Calendar.current.component(.month, from: date) let sameYear = Calendar.current.component(.year, from: item.time) == Calendar.current.component(.year, from: date) let sameDay = Calendar.current.component(.day, from: item.time) == Calendar.current.component(.year, from: date) return sameDay && sameMonth && sameYear }) However, the indices(where:) codeblock seems to stop the app from compiling (ONLY on Swift Playgrounds - it works perfectly fine on XCode). I am getting the following error: Cannot call value of non-function type 'Range<Array<Int>.Index>' (aka 'Range<Int>') Please let me know if you have any insight regarding this issue. -ColoredOwl
2
1
475
Jan ’25
Swift playground + metal crashes on swift 6
Following code crashes (sigsegv in lldb-rpc-server) when run as swift 6, but runs correctly when run as swift 5 (from "Metal by tutorials"): import PlaygroundSupport import MetalKit print("start") guard let device = MTLCreateSystemDefaultDevice() else { fatalError("GPU is not supported") } let frame = CGRect(x: 0, y: 0, width: 600, height: 600) let view = MTKView(frame: frame, device: device) view.clearColor = MTLClearColor(red: 1, green: 1, blue: 0.8, alpha: 1) let allocator = MTKMeshBufferAllocator(device: device) let mdlMesh = MDLMesh(sphereWithExtent: [0.75,0.75,0.75], segments: [100, 100], inwardNormals: false, geometryType: .triangles, allocator: allocator) let mesh = try MTKMesh(mesh: mdlMesh, device: device) guard let commandQueue = device.makeCommandQueue() else { fatalError("Could not create a command queue") } let shader = """ #include <metal_stdlib> using namespace metal; struct VertexIn { float4 position [[attribute(0)]]; }; vertex float4 vertex_main(const VertexIn vertex_in [[stage_in]]) { return vertex_in.position; } fragment float4 fragment_main() { return float4(1, 0, 0, 1); } """ print("A") let library = try device.makeLibrary(source: shader, options: nil) let vertexFunction = library.makeFunction(name: "vertex_main") let fragmentFunction = library.makeFunction(name: "fragment_main") let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineDescriptor.vertexFunction = vertexFunction pipelineDescriptor.fragmentFunction = fragmentFunction print("X") pipelineDescriptor.vertexDescriptor = MTKMetalVertexDescriptorFromModelIO(mesh.vertexDescriptor) let pipelineState = try device.makeRenderPipelineState(descriptor: pipelineDescriptor) guard let commandBuffer = commandQueue.makeCommandBuffer(), let renderPassDescriptor = view.currentRenderPassDescriptor, let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { fatalError() } renderEncoder.setRenderPipelineState(pipelineState) renderEncoder.setVertexBuffer(mesh.vertexBuffers[0].buffer, offset: 0, index: 0) guard let submesh = mesh.submeshes.first else { fatalError() } renderEncoder.drawIndexedPrimitives(type: .triangle, indexCount: submesh.indexCount, indexType: submesh.indexType, indexBuffer: submesh.indexBuffer.buffer, indexBufferOffset: 0) renderEncoder.endEncoding() guard let drawable = view.currentDrawable else { fatalError() } commandBuffer.present(drawable) commandBuffer.commit() print("test") PlaygroundPage.current.liveView = view Crash report: https://gist.githubusercontent.com/tumdum/8aa53bc806619c0d21c93a55fae07937/raw/370b00c07b08fff8856f9fc678de9888faa8d06e/crash.log I'm on macOS 15.1.1 (24B2091) + Xcode 16.2 (16C5032a)
1
1
339
Feb ’25
Can we use Multipeer Connectivity framework and opensource packages for Swift Student Challenge?
I am building an app playground for SSC'25 where I want to use Multipeer Connectivity framework that would allow me to send and receive data to and from stranger devices. I also want to use some other open-source packages for some of the features. I just wanted to know if we are allowed to use or not?
4
0
734
Jan ’25
Comparing colors of two ModelEntities
I want to compare the colors of two model entities (spheres). How can i do it? The method i'm currently trying to apply is as follows case let .color(controlColor) = controlMaterial.baseColor, controlColor == .green { // Flip target sphere colour if let targetMaterial = targetsphere.model?.materials.first as? SimpleMaterial, case let .color(targetColor) = targetMaterial.baseColor, targetColor == .blue { targetsphere.model?.materials = [SimpleMaterial(color: .green, isMetallic: false)] // Change to |1⟩ } else { targetsphere.model?.materials = [SimpleMaterial(color: .blue, isMetallic: false)] // Change to |0⟩ } } This method (baseColor) was deprecated in swift 15.0 changes to 'color' but i cannot compare the value color to each other.👾
1
0
603
Jan ’25
Cannot assign build target to usdz file
I’m working in the app playground and want to add my usdz file but when i drag drop the file to my main folder i cannot add target to it which leads to a resource not found error while I build my app. It was working on a normal xcode project but while transitioning to app playground it is not working. How can I fix this issue?
0
0
350
Jan ’25
Swift Playgrounds Will Not Upload to App Store Connect
When I go to the App Settings menu in Swift Playgrounds and attempt to upload to App Store Connect, I run into the below error screen: I am registered with the Apple Developer Program. Swift Playgrounds is updated to its latest version. This is occurring on both macOS and iPadOS. All the information I put in is valid. Any reason why this would be happening?
2
1
349
Jan ’25
Swift/ Swift UI errors.
Hi everyone, I am a new developer. I am writing some code in swift playgrounds and came across some odd errors. I have looked for solutions and have found nothing. If any more experienced developers could point me in the right direction, that would be great.
4
0
485
Dec ’24
Can not use or do anything on the Playgrounds app on iPad Air M2 running iPadOS 18.3 beta
Hi, I have recently downloaded the app to start learning how to code in swift and so on. On my first try I have gotten the error stating that ”.swiftpm files cannot be opened”. I have followed some forum posts. I restarted my iPad several times and redown the app several times. I tried to disable the iCloud sync but I think I deleted the iCloud directory entirely that just results in the app closing on any action taken. (such as pressing the “New App” option or choosing the quick actions to make apps). Is there a way to fix this? Any help is appreciate, please ask me to provide any extra needed information.
1
0
452
Jan ’25
Using Core ML in a .swiftpm file
Hi everyone, I've been struggling for a few weeks to integrate my Core ML Image Classifier model into my .swiftpm project, and I’m hoping someone can help. Here’s what I’ve done so far: I converted my .mlmodel file to .mlmodelc manually via the terminal. In my Package.swift file, I tried both "copy" and "process" options for the resource. The issues I’m facing: When using "process", Xcode gives me the error: "multiple resources named 'coremldata.bin' in target 'AppModule'." When using "copy", the app runs, but the model doesn’t work, and the terminal shows: "A valid manifest does not exist at path: .../Manifest.json." I even tried creating a Manifest.json manually to test, but this led to more errors, such as: "File format version must be in the form of major.minor.patch." "Failed to look up root model." To check if the problem was specific to my model, I tested other Core ML models in the same setup, but none of them worked either. I feel stuck and unsure of how to resolve these issues. Any guidance or suggestions would be greatly appreciated. Thanks in advance! :)
2
2
1k
Jan ’25
Vision Framework Causes EXC_BREAKPOINT Error in Xcode App Playground (.swiftpm) File
I’m trying to use the Vision framework in a Swift Playground to perform face detection on an image. The following code works perfectly when I run it in a regular Xcode project, but in an App Playground, I get the error: Thread 12: EXC_BREAKPOINT (code=1, subcode=0x10321c2a8) Here's the code: import SwiftUI import Vision struct ContentView: View { var body: some View { VStack { Text("Face Detection") .font(.largeTitle) .padding() Image("me") .resizable() .aspectRatio(contentMode: .fit) .onAppear { detectFace() } } } func detectFace() { guard let cgImage = UIImage(named: "me")?.cgImage else { return } let request = VNDetectFaceRectanglesRequest { request, error in if let results = request.results as? [VNFaceObservation] { print("Detected \(results.count) face(s).") for face in results { print("Bounding Box: \(face.boundingBox)") } } else { print("No faces detected.") } } let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) do { try handler.perform([request]) // This line causes the error. } catch { print("Failed to perform Vision request: \(error)") } } } The error occurs on this line: try handler.perform([request]) Details: This code runs fine in a normal Xcode project (.xcodeproj). I'm using an App Playground instead (.swiftpm). The image is being included in the .xcassets folder. Is there any way I can mitigate this issue? Please do not recommend switching to .xcodeproj, as I am making a submission for Apple's Swift Student Challenge, and they require that I use .swiftpm.
1
0
389
Dec ’24
Playground created on iPad not opening on Mac
I've entered some code on Version 4.5.1 of Playgrounds on my iPad mini running iOS 18.1.1. The file is saved on iCloud and so is available on my Mac running OS 15.2. However, the file will not open in either Playgrounds v 4.5.1 on the Mac (error "Unable to get file wrapper for contents.xcplayground.") or Xcode 16.1 (error "Couldn't load settings from contents.xcplayground"). The file's type is .playgorund. Any thoughts?
1
0
430
Jan ’25
Swift Playgrounds Incompatibility with Xcode 16 Files and Swift Versions
I'm facing an issue with Swift Playgrounds and files created in Xcode 16. It seems that Swift Playgrounds does not support Swift 6, but even when I create files specifically with Swift 5, Swift Playgrounds still reports that the files are unsupported. This creates a significant problem because macOS Sequoia does not allow me to revert to Xcode 15, which might have offered better compatibility. As it stands, I can't find a solution to work seamlessly between Xcode and Swift Playgrounds. Has anyone else encountered this issue? Are there any workarounds or updates planned to address this compatibility gap? Any advice would be greatly appreciated!
4
1
752
Jan ’25
Why am I unable to render .dae file in Playground?
This is my code in ContentView: import SwiftUI import SceneKit import PlaygroundSupport struct ContentView: View { var body: some View { VStack { Text("SceneKit with SwiftUI") .font(.headline) .padding() SceneView( scene: loadScene(), options: [.autoenablesDefaultLighting, .allowsCameraControl] ) .frame(width: 400, height: 400) .border(Color.gray, width: 1) } } } func loadScene() -> SCNScene? { if let fileURL = Bundle.main.url(forResource: "a", withExtension: "dae") { do { let scene = try SCNScene(url: fileURL, options: [ SCNSceneSource.LoadingOption.checkConsistency: true ]) print("Scene loaded successfully.") return scene } catch { print("Error loading scene: \(error.localizedDescription)") } } else { print("Error: Unable to locate a.dae in Resources.") } return nil } a.dae file exists in the Resources section of macOS Playground app. And a.dae can be viewed in Xcode. Console shows: Error loading scene: The operation couldn’t be completed. (Foundation._GenericObjCError error 0.) Any input is appreciated.
1
0
477
Dec ’24