Swift Playgrounds

RSS for tag

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

Swift Playgrounds Documentation

Posts under Swift Playgrounds tag

279 Posts
Sort by:
Post not yet marked as solved
2 Replies
225 Views
Hello world! I was creating a playground with Swift Playgrounds, and I created a .swift files and should connect these files to ContentView(), but when I write that file name on ContentView() it tells me "Cannot find ... in scope". Does anyone know why this error and how to fix it? Thanks in advance from heart.
Posted Last updated
.
Post not yet marked as solved
2 Replies
257 Views
İ am getting "Failed to produce a diagnostic for expression; please file a bug report" error. import SwiftUI struct ContentView: View {     let lifeformanalyzer = Lifeformanalyzer()     @State var text = ""     @State var title = "Merhaba insan!"          var body: some View { ————> error is here         VStack {             Image(systemName: "face.smiling.fill")                 .imageScale(.large)                 .foregroundColor(.accentColor)                 .padding(.top, 50)             Text(title)                 .font(.largeTitle)                          Spacer()                          TextField("Birşey yazın", text: $text)                 .multilineTextAlignment(.center)                 .frame(width: 300)                          Spacer()                          Button("Gönder") {                 submit()             }                          Spacer()                      }                                   .padding()         .frame(maxWidth: .infinity, maxHeight: .infinity)         .background(Color(red: 0.024, green: 0.392, blue: 0.549))         .ignoresSafeArea()                  func submit() {                      }     var title = "Merhaba \(lifeformanalyzer.processLifeform(text: text))!"                       }                     } The other swift file Lifeformanalyzer: class Lifeformanalyzer {          func processLifeform(text: String) -> String{                  text.lowercased().contains("vak")         ? "ördek" : "insan"     } }
Posted Last updated
.
Post marked as solved
1 Replies
210 Views
I've encountered an issue where a swift playground app (when run in its own window) becomes unresponsive after approximately 3 minutes. The window goes dim and the playground ceases to respond. The HUD automatically comes down to suggest restarting the code. No error in my code is reported, and I seem to only ever encounter this issue when running from Swift Playgrounds on iPad (not an issue on Xcode). I know there is a 3 minute limit anyway for the Swift Student Challenge, but is anyone else experiencing the same issue? if not, any thoughts on possible causes of this?
Posted Last updated
.
Post marked as solved
2 Replies
338 Views
I'm constructing a Swift Playground with UIKit that contains an SKScene. After creating the code I'm planning to use within an Xcode project, I tried to adapt it into my Playground. I encountered an issue while running the Playground - when a new SKSpriteNode is added to the Scene, the new and existing nodes jitter, freeze, and lag for a split-second, the FPS counter drops to around 49fps, then returns to smooth 60fps. No errors or warnings are spat, and the console is completely empty. The scene in the project didn't have this issue, and I can't recreate it on another project - even when I directly copy-paste the code from the Playground to the project. I've seen other posts with this question - and made a few myself elsewhere - and there's been no responses. I desperately need help for this as nothing I've tried is working and the deadline is in a few days! Thanks! The code that is in effect for this SKScene is below. class SimulatorController: UIViewController { override func loadView() { let view = SKView() let scene = GameScene(size: view.bounds.size) view.showsFPS = true view.showsNodeCount = true view.ignoresSiblingOrder = true scene.scaleMode = .resizeFill view.presentScene(scene) self.view = view } } class GameScene: SKScene { override func didMove(to view: SKView) { run(SKAction.repeatForever(SKAction.sequence([ SKAction.run(addNeutron), SKAction.wait(forDuration: 1) ]) )) } func random() -> CGFloat { return CGFloat(Float(arc4random()) / 0xFFFFFFFF) } func random(min: CGFloat, max: CGFloat) -> CGFloat { return random() * (max - min) + min } func addNeutron() { let neutron = SKSpriteNode(imageNamed: "neutron.heic") neutron.size = CGSize(width: 20, height: 20) neutron.physicsBody = SKPhysicsBody(rectangleOf: neutron.size) neutron.physicsBody?.isDynamic = true let actualX = random(min: 0, max: size.width) let actualY = random(min: 0, max: size.height) neutron.position = CGPoint(x: actualX, y: actualY) addChild(neutron) let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0)) let actualX2 = random(min: 0, max: size.width) let actualY2 = random(min: 0, max: size.height) let actionMove = SKAction.move(to: CGPoint(x: actualX2, y: actualY2), duration: TimeInterval(actualDuration)) let actionMoveDone = SKAction.removeFromParent() neutron.run(SKAction.sequence([actionMove, actionMoveDone])) } }
Posted Last updated
.
Post marked as solved
2 Replies
302 Views
My playground app runs perfectly fine when I compile it on Xcode on my Mac to run it on my iPad, but for some reason it won't run at all when I try running it directly on Swift Playgrounds (the file opens and it doesn't give me any errors, but it won't compile). How might I be able to fix this? My app is a .swiftpm file and I'm using Swift Playgrounds 4.0.2 on iPadOS 15.4.1. Any help would be greatly appreciated!
Posted
by CodeSwift.
Last updated
.
Post marked as solved
1 Replies
181 Views
Hello there! I would like to set an image as the background of my project in SwiftUI, but I have no idea how it is done. Could anyone help me to figure out this? I am using Swift Playgrounds and SwiftUI framework.
Posted Last updated
.
Post not yet marked as solved
0 Replies
300 Views
I try to transfer this Xcode sample project to the Playground app project. However, when I move all swift files and the CoreML file called 'ExerciseClassifier.mlmodel' on the folder to the Playground app project, it shows the error, "Cannot find type 'ExerciseClassifier' in scope". What could I do to remove the error and make a proper working project on Playground?
Posted
by yerin16.
Last updated
.
Post marked as solved
2 Replies
509 Views
Hi !, For this year's WWDC Student challenge we need to create a swift playgrounds app but I have designed a swift playground book with chapters and multiple pages. Now I need to convert it into the swift playgrounds app, How can I do it ? I am completely new to swift and Xcode. Just started to learn swift about 15 days ago. So any help would be appreciated Thanks in advance cheers, Sanjiv Anand
Posted Last updated
.
Post marked as solved
1 Replies
149 Views
editDistance() -> https://github.com/raywenderlich/swift-algorithm-club/tree/master/Minimum%20Edit%20Distance It’s license -> https://github.com/raywenderlich/swift-algorithm-club/blob/master/LICENSE.txt // Looks through the potentialMatches array to find the item that most closely matches the string in the first argument, and returns that string. func closestMatch(for string: String, from potentialMatches: [String]) -> String {     // Initialize the best edit distance to the worst possible value     var bestEditDistance = Int.max     // Initialize the index of the best match to the first index     var bestMatchIndex = 0          for i in 0 ..< potentialMatches.count {         // Get the potential match at index i                  // Get the edit distance from the string to the potential match                  // If the distance calculated above is better than best edit distance,         // update the best edit distance and best match index         let potentialMatch = potentialMatches[i]         let distance = editDistance(from: string, to: potentialMatch)                  if distance < bestEditDistance {             bestMatchIndex = i             bestEditDistance = distance         }     }          return potentialMatches[bestMatchIndex] } Could you please explain why we initialize bestEditDistance like Int.max ? I don't understand what does this instance mean.
Posted Last updated
.
Post marked as solved
2 Replies
184 Views
I was doing an exercise about cleaning data. This is a previous code for searching data errors that works correctly: // Create a Tabulator instance. var tabulator = Tabulator() // Loop through surveyData, incrementing the count for each response. for data in surveyData {     tabulator.incrementCount(forValue: data) } // Loop through the tallied shows (stored in tabulator.values), printing the information from each one. for i in tabulator.values {     tabulator.count(forValue: i) } showCatalog print("\n\n***** FIRST CLEANING PASS *****\n\n") // Print a header print("\n\n***** TABULATION FOR VALID DATA ******\n\n") showCatalog // Loop through all tabulator values. Only print the count for those that are contained in showCatalog. var k_normal = 0 var k_bad = 0 for a in tabulator.values {     if showCatalog.contains(a) == true {         k_normal += 1     } else {         k_bad += 1         print(a)         print(k_bad)     } } // Create a variable to keep a count of the errors. // Print a header print("\n\n***** DATA ERRORS ******\n\n") // Loop through all tabulator values. // If a value is not contained in showCatalog: // - Increase the error count // - Print it // Print the error count. Then I have a new exercise: Some of the errors in the data seem to be simple capitalization mistakes. You've already seen a way to solve such problems in the QuestionBot app: Just convert the string to lowercase. First, you'll need to have a lowercased version of your show catalog. Recall that you can create a lowercase string by using the lowercased() method. Create a new catalog containing lowercased versions of all the shows.You should see the error count go from 13 down to just 3. This is my next code that doesn't execute any correct or incorrect inputs. Please help me with that. // Make a new array variable. var newArray: [String] = [] // For all shows in showCatalog, add a lowercase version to the array. for shows in showCatalog {     shows.lowercased()     newArray.append(shows.lowercased()) } newArray // Create a Tabulator instance. var tabulator = Tabulator() // Loop through surveyData. Make a lowercase version of each value, then increment its count. for data in newArray {     tabulator.incrementCount(forValue: data) } // Loop through all tabulator values. Print only those that are contained in the lowercase version of the show catalog. var k_normal = 0 var k_bad = 0 for a in tabulator.values {     if newArray.contains(a) == true {         k_normal += 1     } else {         k_bad += 1         print(a)     } } // Print a header print(k_normal) print(k_bad) // Create a variable to keep a count of the errors. // Loop through all tabulator values. // If a value is not contained in the lowercase show catalog: // - Increase the error count // - Print it // Print the error count.
Posted Last updated
.
Post marked as solved
5 Replies
365 Views
Hi, I have installed Swift Playgrounds on my iPad and I would like to create an app that displays a webpage (html). I tried several code found on the web, like this below, but does not work. import WebKit class ViewController: UIViewController, WKUIDelegate { var webView: WKWebView! override func loadView() { let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = self view = webView } override func viewDidLoad() { super.viewDidLoad() let myURL = URL(string:"https://www.apple.com") let myRequest = URLRequest(url: myURL!) webView.load(myRequest) }} Is it possible to create an app on Swift Playgrounds for iPad that lauch a html page in a webView ? Thanks for your help.
Posted
by dom063.
Last updated
.
Post not yet marked as solved
0 Replies
246 Views
Dear Teams, I try to transfer this Xcode sample project to the Playground app project. However, when I move all swift files and the CoreML file called 'ExerciseClassifier.mlmodel' on the folder to the Playground app project, it shows the error, "Cannot find type 'ExerciseClassifier' in scope". What could I do to remove the error and make a proper working project on Playground? Thanks.
Posted
by yerin16.
Last updated
.
Post not yet marked as solved
2 Replies
825 Views
Hello, We are modularizing our iOS project using SPM. One of those modules is our UI module, which contains a bunch of Resources, for example, custom fonts. In order to register the fonts, we use the following code to access the resources: swift Bundle.module.urls(forResourcesWithExtension: "otf", subdirectory: nil) This is the recommended way from Apple as seen here - https://developer.apple.com/videos/play/wwdc2020/10169/. This seems to be working when importing the module into our main app. The problem appears when this code is executed from a Playground within the same module. When the code is executed, a fatal error is thrown: unable to find bundle named UniverseUI_UniverseUI This is triggered from the generated file resource_bundle_accessor.swift which contains the following code: swift import class Foundation.Bundle private class BundleFinder {} extension Foundation.Bundle {     /// Returns the resource bundle associated with the current Swift module.     static var module: Bundle = {         let bundleName = "UniverseUI_UniverseUI"         let candidates = [             // Bundle should be present here when the package is linked into an App.             Bundle.main.resourceURL,             // Bundle should be present here when the package is linked into a framework.             Bundle(for: BundleFinder.self).resourceURL,             // For command-line tools.             Bundle.main.bundleURL,         ]         for candidate in candidates {             let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")             if let bundle = bundlePath.flatMap(Bundle.init(url:)) {                 return bundle             }         }         fatalError("unable to find bundle named UniverseUI_UniverseUI")     }() } Lastly, our module target defines resources like so: swift resources: [.process("Resources")]), Is there any workaround so we don't trigger the fatalError when executing that code from a playground? Any check to know if Bundle.module is available? Thank you
Posted
by vbaro.
Last updated
.
Post not yet marked as solved
1 Replies
160 Views
Hi all, Need to upgrade. And instead of a new Mac I'm thinking iPad Pro (M1 chip). But, very important question: can I run my existing Xcode projects on the iPad Pro with Swift Playgrounds (4)? And install/distribute the app to the iPhone from the iPad Pro?
Posted
by MSune.
Last updated
.
Post not yet marked as solved
0 Replies
159 Views
Greetings, I want to force my app's Orientation. Most solutions for "How to force orientation to Landscape for SwiftUI" seems works only for "real" SwiftUI project, not .swiftpm How can I force orientation to landscape for Swift Playground App Project?
Posted Last updated
.