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

Swift Documentation

Posts under Swift tag

2,710 results found
Sort by:
Post not yet marked as solved
8 Views

What is the syntax for "if not" in Swift?

I have the code below which works just fine. getTwinklingGem returns type MyGem. What I cannot figure out is if there is a proper syntax for writing the NOT into the if statement. Am still too new to Swift. This works, but seems lengthy: if let twinkling = getHighGem(), twinkling != nil Is this the proper way to test for a nil return? if let twinkling = getHighGem() as? MyGem if let twinkling = getTwinklingGem() { print ("not nil") }
Asked
by SergioDCQ.
Last updated
.
Post marked as solved
26 Views

How can I return a nil in Swift

I have a subclass of SKSpriteNode called MyGem. There are multiple instances of this class at runtime. They are all in an array of MyGems. At a specific point I would like to find out which MyGem is twinkling. The problem I am running into is if no MyGem is twinkling. What do I return? I can't return a nil. 'nil' is incompatible with return type 'MyGem' So what do I return? I thought of returning the index number of the MyGem in the array class, and then passing -1 if none were twinkling. But that seems kludgy. func getHighGem() -> MyGem {    for gem in myGems {     if gem.twinkling == true {     return gem       }    }     return nil //this line causes the IDE error }
Asked
by SergioDCQ.
Last updated
.
Post not yet marked as solved
83 Views

@SectionedFetchRequest using relationship as sectionIdentifier

As the title says I'm trying to use a to-one relationship as a sectionIdentifier in a @SectionedFetchRequest. The compiler is happy but there's a runtime crash: Could not cast value of type '_NSCoreDataTaggedObjectID' (0x146c0f750) to 'MyApp.ServiceCategory' (0x104c4b3a0). The fetch request: @SectionedFetchRequest(     sectionIdentifier: \Service.serviceCategory,     sortDescriptors: [       SortDescriptor(\Service.active, order: .reverse),       SortDescriptor(\Service.displayText)     ],     predicate: NSPredicate(format: "%K = %d", #keyPath(Service.active), true),     animation: .default   ) var sectionedServices: SectionedFetchResults<ServiceCategory?, Service> ... and the breaking runtime code: ForEach(sectionedServices /* here */) { section in Section(header: Text(section.id?.displayText ?? "")) { ForEach(section) { svc in Text(svc.displayText ?? "") } } } The request works if I switch out the sectionIdentifier for the active property (which is a Bool property rather than a relationship). It also works if I switch it out for displayText which is an optional String, so it seems to be a problem trying to section by a relationship rather than with it being an optional. The error suggests the request is returning a Core Data fault rather than an object but my attempts to somehow unwrap this haven't gone very far. Any thoughts would be greatly appreciated!
Asked
by robwuk.
Last updated
.
Post not yet marked as solved
18 Views

Crash in processDefaultActor

I am getting a strange crash (see call stack in attached screenshot). I am looking for ideas/hints how to track down what the issue is?
Asked
by milutz.
Last updated
.
Post not yet marked as solved
102 Views

Form vs Vstack for SwiftUI for iOS

I'm building a View for account creation, and have a number of text fields (first name, last name, email, etc.). It seems like the natural choice is to embed these TextField() views into a Form, but given that Form is built on UITableView (as I understand it) it becomes challenging and requires some workarounds to add modifiers like .background() and have them perform the way I want them to. If, instead of embedding them in a Form, I just use a VStack, there's no problem. So my question is, is there any reason I should put up with the trouble and use Form? Does it give me any added functionality? Is it considered bad or unclean code to not use Form? From what I can tell, there don't seem to be any real benefits, right?
Asked
by Shen3443.
Last updated
.
Post not yet marked as solved
21 Views

WKWebView target blank blob:

Hi, In my WKWebView I can't open blob links if there is target blank. a href="https://..." --> ok <a href="https://..." target="_blank" --> ok a href="blob:..." --> ok a href="blob:..." target="_blank" --> NOK!!! I've implemented this method : func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { print("\n=================\nTARGET BLANK\n") ... } In case of a href="blob:..." target="_blank" I don't have any print in the console. Could you help me ? Julien
Asked
by ju-dev.
Last updated
.
Post not yet marked as solved
62 Views

SwiftUI: Markdown support for string variables

Text in iOS 15 Beta 1 (Xcode 13 Beta 1) only handles markdown when string literal was passed to initializer. struct MarkdownTest: View {   var text: String = "**Hello** *World*"   var body: some View {     VStack {       Text("**Hello** *World*") // will be rendered with markdown formatting       Text(text) // will NOT be rendered according to markdown     }   } } struct MarkdownTestPreviews: PreviewProvider {   static var previews: some View {     MarkdownTest()   } } Is this a known bug or do I have to create an entry in Feedback Assistant?
Asked Last updated
.
Post not yet marked as solved
16 Views

[Unity-2018.4.10f1] - Issue with Swift Version when Export to Xcode

Hello I got the problem that the Xcode does not support the Swift version 3.0 on Xcode version 12.5 Is there any way to config the Swift version on Unity? Or how to determine which plugin using Swift version 3.0 in Unity Project?
Asked
by thaitam.
Last updated
.
Post not yet marked as solved
21 Views

swift Maybe sampleBuffer release and then it crash

public func writeData(connection: AVCaptureConnection, video: AVCaptureConnection, audio: AVCaptureConnection, buffer: CMSampleBuffer, isFrontPosition: Bool = false) {     movieWritingQueue.async { [weak self] in       guard let self = self else { return }       self.numberOfThread += 1       if connection == video {         if !self.readyToRecordVideo {           if let sample = CMSampleBufferGetFormatDescription(buffer) {             self.readyToRecordVideo = (self.setupAssetWriterVideoInput(sample)) == nil           }         }         if self.inputsReadyToRecord() {           self.writeSampleBuffer(sampleBuffer: buffer, mediaType: .video)         }       } else if connection == audio {         if !self.readyToRecordAudio {                       if let sample = CMSampleBufferGetFormatDescription(buffer) {             self.readyToRecordAudio = (self.setupAssetWriterAudioInput(sample)) == nil           }                     }         if self.inputsReadyToRecord() {           self.writeSampleBuffer(sampleBuffer: buffer, mediaType: .audio)         }       }     }   }       public func writeSampleBuffer(sampleBuffer: CMSampleBuffer, mediaType: AVMediaType) {     if movieWriter?.status == .unknown {       if let mw = movieWriter, mw.startWriting() {         mw.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sampleBuffer))       } else {         logger.i(" --- \(String(describing: movieWriter?.error)) --- ")       }     }           if movieWriter?.status == .writing {       var isVideo = false       if mediaType == .video {         isVideo = true       }               let sampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)       let last = isVideo ? lastVideoTimeOrigin : lastAudioTimeOrigin       if let lastTime = last, lastTime.isValid, lastTime.seconds != 0 {         let lastSecond = lastTime.seconds         let sampleSecond = sampleTime.seconds         if sampleSecond - lastSecond < 0.0016 {           print("drop")           return         }       }               // 记录暂停上一次录制的时间       var ptsOrigin = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)       let durOrigin = CMSampleBufferGetDuration(sampleBuffer)       if durOrigin.value > 0 {         ptsOrigin = CMTimeAdd(ptsOrigin, durOrigin)       }       if isVideo {         lastVideoTimeOrigin = ptsOrigin       } else {         lastAudioTimeOrigin = ptsOrigin       }               if isDiscont {         isDiscont = false         // 计算暂停的时间         var pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)         let last = isVideo ? lastVideoTime : lastAudioTime         if let last = last, last.isValid {           if let timeOffset = timeOffset, timeOffset.isValid {             pts = CMTimeSubtract(pts, timeOffset)           }           let offset = CMTimeSubtract(pts, last)           if timeOffset?.value == 0 {             timeOffset = offset           } else {             timeOffset = CMTimeAdd(timeOffset ?? CMTime(), offset);           }         }         lastVideoTime?.flags = .valid         lastAudioTime?.flags = .valid       }               var copyBuffer = sampleBuffer       if timeOffset?.value ?? CMTime().value > 0 {         //根据得到的timeOffset调整         if let buffer = adjustTime(sample: copyBuffer, offset: timeOffset) {           //copyBuffer = buffer         }       }       // 记录暂停上一次录制的时间       var pts = CMSampleBufferGetPresentationTimeStamp(copyBuffer)       let dur = CMSampleBufferGetDuration(copyBuffer)       if dur.value > 0 {         pts = CMTimeAdd(pts, dur)       }       if isVideo {         lastVideoTime = pts       } else {         lastAudioTime = pts       }               if mediaType == .video {         guard let mvi = movieVideoInput, mvi.isReadyForMoreMediaData else { return }         if !mvi.append(copyBuffer) {           logger.i(" --- \(String(describing: movieWriter?.error)) --- ")         }       } else if mediaType == .audio {         guard let mai = movieAudioInput, mai.isReadyForMoreMediaData else { return }         if !mai.append(copyBuffer) {           logger.i(" --- \(String(describing: movieWriter?.error)) --- ")         }       }         //      var copyBuffer: CMSampleBuffer? = sampleBuffer //      CMSampleBufferCreateCopy(allocator: nil, sampleBuffer: sampleBuffer, sampleBufferOut: &copyBuffer) //      if timeOffset?.value ?? CMTime().value > 0 { //        //根据得到的timeOffset调整 //        if let buffer = adjustTime(sample: copyBuffer, offset: timeOffset) { //          copyBuffer = buffer //        } //      } //      guard let buffer = copyBuffer else { //        return //      } //      // 记录暂停上一次录制的时间 //      var pts = CMSampleBufferGetPresentationTimeStamp(buffer) //      let dur = CMSampleBufferGetDuration(buffer) //      if dur.value > 0 { //        pts = CMTimeAdd(pts, dur) //      } //      if isVideo { //        lastVideoTime = pts //      } else { //        lastAudioTime = pts //      } // //      if mediaType == .video { //        guard let mvi = movieVideoInput, mvi.isReadyForMoreMediaData else { return } //        if !mvi.append(buffer) { //          logger.i(" --- \(String(describing: movieWriter?.error)) --- ") //        } //      } else if mediaType == .audio { //        guard let mai = movieAudioInput, mai.isReadyForMoreMediaData else { return } //        if !mai.append(buffer) { //          logger.i(" --- \(String(describing: movieWriter?.error)) --- ") //        } //      } //      copyBuffer = nil     }   }       //调整媒体数据的时间   func adjustTime(sample: CMSampleBuffer?, offset: CMTime?) -> CMSampleBuffer? {     guard let sample = sample, let offset = offset else {       return nil     }     var count: CMItemCount = 0     CMSampleBufferGetSampleTimingInfoArray(sample, entryCount: 0, arrayToFill: nil, entriesNeededOut: &count)     let pInfo = UnsafeMutablePointer<CMSampleTimingInfo>.allocate(capacity: MemoryLayout.size(ofValue: CMSampleTimingInfo.self) * count)     CMSampleBufferGetSampleTimingInfoArray(sample, entryCount: count, arrayToFill: pInfo, entriesNeededOut: &count)     for index in 0...count {       pInfo[index].decodeTimeStamp = CMTimeSubtract(pInfo[index].decodeTimeStamp, offset)       pInfo[index].presentationTimeStamp = CMTimeSubtract(pInfo[index].presentationTimeStamp, offset)     }     var sout: CMSampleBuffer?     CMSampleBufferCreateCopyWithNewTiming(allocator: nil, sampleBuffer: sample, sampleTimingEntryCount: count, sampleTimingArray: pInfo, sampleBufferOut: &sout)     pInfo.deallocate()     return sout   } i need pause when i take movie ,then i need change sampleBuffers timestamp. but when i add the adjust func. thread crash. i guess the sampleBuffer release before i use it so i try to copy it ,but when i copy the sampleBuffers .the buffers all drop. the reason is outofBuffers . when i used objc, i use CFRetain(). but i cant find that func in swift and i use DispatchQueue, so i cant find exactly where crash
Asked
by ccl444444.
Last updated
.
Post not yet marked as solved
4.7k Views

invalid mode 'kCFRunLoopCommonModes'

invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debugI get this warning when I tap either of the switches shown below. I've tried capturing the switch state in a var and using that to trigger the do/catch statement but no joy. I've even tried pulling the do/catch into separate functions and I still get the warning. Has anybody else run into this and how did you fix it?@IBAction func greetingFormat_Tapped(_ sender: UISwitch) { let theQuery = theTable_Settings.filter(settingID == 1) if sender.isOn { do { if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format &lt;- "true")) &gt; 0 { greetingFormatLabel_Outlet.text = NSLocalizedString("HelloMrSmith_String", comment: "") } else { print("greeting format true not found") } } catch { print("greeting format true update failed! Error: \(error)") } } else { do { if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format &lt;- "false")) &gt; 0 { greetingFormatLabel_Outlet.text = NSLocalizedString("HiJoe_String", comment: "") } else { print("greeting format false not found") } } catch { print("greeting format false update failed! Error: \(error)") } } }@IBAction func nonrefundableSwitch_Tapped(_ sender: UISwitch) { let theQuery = theTable_Settings.filter(settingID == 1) var itsOn: String = "" if sender.isOn { itsOn = "true" } else { itsOn = "false" } if itsOn == "true" { do { if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool &lt;- "true")) &gt; 0 { depositDueLabel_Outlet.text = NSLocalizedString("nonRefunddepositisdue_String", comment: "") } else { print("nonRefundable true not found") } } catch { print("nonRefundable true update failed! Error: \(error)") } } else { do { if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool &lt;- "false")) &gt; 0 { depositDueLabel_Outlet.text = NSLocalizedString("depositisdue_String", comment: "") } else { print("nonRefundable false not found") } } catch { print("nonRefundable false update failed! Error: \(error)") } } }
Asked Last updated
.
Post not yet marked as solved
28 Views

Cancel asyncAfter

DispatchQueue.main.asyncAfter(deadline: .now() + 10) { //code } code within asyncAfter will get executed after 10 seconds. Is there a way to cancel execution before 10 seconds
Asked Last updated
.
Post not yet marked as solved
45 Views

The following simple function will cause Xcode 12E262 to have "Abort: trap 6"

The following simple function will cause Xcode 12E262 to have "Abort: trap 6" during compilation. import UIKit import CoreData class ViewController: UIViewController {     func xyz() {         let container = NSPersistentContainer(name: "xyz")         let batchUpdateRequest = NSBatchUpdateRequest(entityName: "xyz")         let batchUpdateResult = try! container.viewContext.execute(batchUpdateRequest) as? NSBatchUpdateResult         guard let batchUpdateResult = batchUpdateResult else { return }     }     override func viewDidLoad() {         super.viewDidLoad()         // Do any additional setup after loading the view.     } } We will not observe "Abort: trap 6", if under Build Settings, we are using "Optimize for Speed" in Debug, instead of "No Optimization" We can also avoid "Abort: trap 6", if we change the following code guard let batchUpdateResult = batchUpdateResult else { return } to guard let batchUpdateResult2 = batchUpdateResult else { return } May I know, why is it so? A simpler code example to reproduce problem, without CoreData would be import UIKit class ViewController: UIViewController {     func getAny() throws -> Any? {         return nil     }     func xyz() {         let name = try! getAny() as? UIViewController         guard let name = name else { return }     }     override func viewDidLoad() {         super.viewDidLoad()         // Do any additional setup after loading the view.     } }
Asked
by yccheok.
Last updated
.
Post not yet marked as solved
30 Views

How can you send a notification using an if statement.

If my value is higher that 10, a notification should pop up saying, "You are beyond the radius" let value = userLocation.distance(from: pointLocation) if (value > 10){ //trigger notification } I am not sure of how to do this, please help.
Asked Last updated
.
Post not yet marked as solved
51 Views

EventKit Reminders Groups?

I've looked around quite a bit at the EventKit documentation and done all the searching I could think of, as well as examining the EKCalendar and EKEventStore types. Trying to find out how to view, modify, and create groups of reminders lists.
Asked
by pjvf17.
Last updated
.