for-await-in loop not working in Swift 5.5 - ios

I was reading the Concurrency section in the Swift 5.5 documentation (https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID640) and copy pasted this example code in a MacOS command line project:
import Foundation
func someFunction() async throws {
let handle = FileHandle.standardInput // Directly from example
for try await line in handle.bytes.lines { // Directly from example
print(line) // Directly from example
} // Directly from example
}
When I built this I got the following errors:
await must precede try (This is weird considering in the documentation await comes after try)
Expected '{' to start the body of for-each loop
Expected pattern
Value of type 'FileHandle' has no member 'bytes'
I literally copy pasted the code so I shouldn't be getting any such errors. I am using MacOS 11.4 and Xcode version 12.5.1. I downloaded the latest toolchain for Swift 5.5 which was released July 1st, 2021. All the previous code with async and await is working for me. Any idea why this is happening?
Things I've tried so far that have not worked:
Making the function return Void as suggested by Ayrton
Tried adding if #available(macOS 12.0, *) in the function body
I tried extending FileHandle to add conformance to AsyncSequence: extension FileHandle: AsyncSequence { }
It said that FileHandle doesn't conform to AnySequence.

Related

''List<Object?>' is not a subtype of type 'Uint8List?'' on IOS Flutter Platform Channel

NOTE: Please do not do a knee-jerk close recommendation based on "more code required for a minimal reproducible example" especially if you don't understand the question. If you follow my logic, I think you will see that more code is not required.
I'm doing some platform specific Flutter code where I have a platform method "stopRec" (stop recording) which awaits a byte array from the native host.
On the Dart side, it looks like this:
Uint8List? recordedBytes;
recordedBytes = await platform.invokeMethod('stopRec');
As you can see it's expecting to get a byte array (Dart Uint8List) back.
I've written the Android code and it works -- it tests out fine, the recorded bytes come back through and playback correctly.
This is what the Android (Java) code looks like:
byte[] soundBytes = recorder.getRecordedBytes();
result.success(soundBytes);
I hope you understand why "more code" is not yet necessary in this question.
Continuing, though, on the IOS side, I'm getting the following error when calling the platform method:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: type
'List<Object?>' is not a subtype of type 'Uint8List?' in type cast
The Dart line where the error occurs is:
recordedBytes = await platform.invokeMethod('stopRec');
So what is happening is that it's not getting a the Dart Uint8List it expects sent back from IOS.
The IOS code looks like this:
var dartCompatibleAudioBytes:[UInt8]?
var audioBytesAsDataFromRecorder: Data?
// ..... platform channel section
case "stopRec":
self?.stopRec()
result(self?.dartCompatibleAudioBytes!) // <---- wrong data type getting sent back here
break
// ..... platform channel section
private func stopRec() {
myRecorder.stopRecording()
audioBytesAsDataFromRecorder = myRecorder.getRecordedAudioFileBytesAsData()
dartCompatibleAudioBytes = [UInt8] (audioBytesAsDataFromRecorder!)
}
I have tested the same IOS implementation code as a stand-alone IOS app that is not connected to Flutter, so I know that at the end of the the stopRec() method, the dartCompatibleAudioBytes variable does contain the expected data which plays back properly.
I hope you can see why "more code" is still not necessary.
The Dart code works
The Android code Works
The Dart code works together with the Android Code
The IOS code works
The IOS code does NOT work together with the Dart code
Using what I've shown, can anyone see immediately why the expected data type is not making its way back through the method channel?
According to the documentation, you should be using FlutterStandardTypedData(bytes: Data) in swift in order for it to be deserialized as Uint8List in dart.

Issue with String initializer in Swift when using format parameter

I'm getting an error for this line of Swift code in my XCode playground:
print(String(format: "%.2f", 3.345))
The error reads
No exact matches in call to initializer
I believe this means that I haven't used the right parameter names/order to call the initializer. However, when running this line of code while working on an iOS app or even in the online Swift playground http://online.swiftplayground.run/, the line runs without any issues.
When running it in the XCode playground or on my terminal through the Swift REPL however, it throws an error.
Why is this the case?
Foundation has to be imported before using String.
String is a Foundation type in swift.
I was corrected by Matt below in the comments.
String is built into swift and String(format: is in foundation.
I guess that's why the docs didn't show it as such.
Thank you for the correction.

Is Process always unresolved in iOS app or Playground?

In a iOS app, I want to use a file which have an following function using Process:
public func system(_ body: String) throws {
if #available(macOS 10.0, *) {
let process = Process()
...
} else {
fatalError()
}
}
Then, I got a fallowing error even though I applied Availability Condition and I don't evoke this function:
Use of unresolved identifier 'Process'.
I tried a similar code in Playground, and I got the same error.
I learned we cannot use Process in iOS Apps with a regular way by this question: How to execute terminal commands in Swift 4? , and I have a solution that I separate these codes with files by each using platforms. But I want to use this single file if I can.
Please give me your another solution for my ideal.
if #available() does a runtime check for OS versions.
if #available(macOS 10.0, *)
evaluates to true if the code is running on macOS 10.0 or later,
or on iOS/tvOS/watchOS with an OS which is at least the minimum deployment target.
What you want is a conditional compilation, depending on the platform:
#if os(macOS)
let process = Process()
#else
// ...
#endif
Even though you already solved this problem, just for you to know, I want to tell you that actually, Process() (or CommandLine() in Swift 3.0 or newer) is available for iOS, but you'll need to use a custom Objective-C header file which creates the object Process()/CommandLine(), or rather NSTask(), and everything it needs.
Then, in order to use this code with Swift, you'll need to create a Bridging-Header, in which you'll need to import the NSTask.h file for it to be exposed to Swift and being able to use it in your Swift code.
Once done this, use NSTask() instead of Process():
let process = NSTask() /* or NSTask.init() */
Or just use the following function in your code whenever you want to run a task:
func task(launchPath: String, arguments: String...) -> NSString {
let task = NSTask.init()
task?.setLaunchPath(launchPath)
task?.arguments = arguments
// Create a Pipe and make the task
// put all the output there
let pipe = Pipe()
task?.standardOutput = pipe
// Launch the task
task?.launch()
task?.waitUntilExit()
// Get the data
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
return output!
}
As you can see, NSTask() would be the equivalent to Process() in this case.
And call it like this:
task(launchPath: "/usr/bin/echo", arguments: "Hello World")
This will also return the value, so you can even display it by doing:
print(task(launchPath: "/usr/bin/echo", arguments: "Hello, World!"))
Which will print:
~> Hello, World!
For this to work and not throwing an NSInternalInconsistencyException, you'll need to set the launchPath to the executable's full path instead to just the directory containing it.
You'll also need to set all the command arguments separated by commas.
Tested on both iPad Mini 2 (iOS 12.1 ~> Jailbroken) and iPhone Xr (iOS 12.2 ~> not jailbroken).
NOTE: Even though this works both on non-jailbroken and jailbroken devices, your App will be rejected on the AppStore, as #ClausJørgensen said:
You're using private APIs, so it'll be rejected on the App Store. Also, Xcode 11 has some new functionality that will trigger a build failure when using certain private APIs.
If your app is targeting jailbroken iOS devices and will be uploaded to a third-party store like Cydia, Zebra, Thunderbolt or Sileo, then this would work correctly.
Hope this helps you.

Swift 2 - replacement for the deprecated function extend (Swiftache)

I have Swiftache in my Swift 2 project, and after the Xcode 7 update, the following line is complaining (the error is there is no longer an extend method).
public func renderText(text: String) {
if !renderable {
return
}
_text.extend(text)
}
So _text.extend(text) is the offending line. What could I replace it with?
What did the extend method even do, originally? I can't find an equivalent because I'm not familiar with the original method back when it worked in the older version of Xcode.
Thanks!

unable to execute command: Segmentation fault: 11 swift frontend command failed due to signal (use -v to see invocation)

I have an iOS swift program that compiles and runs fine on Xcode Beta2. When I downloaded beta4, I got a few syntax errors for the new swift language which I corrected. I now get this error:
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
The problem is that it does not tell me where this error is so that I can further troubleshoot it. Where can I type -v in order to "see the invocation" and troubleshoot further? Without this, there is absolute no way to figure out the problem. Thanks in advance.
Here's how I was able to find out what the problem was:
Click on the issue in the issue navigator (⌘ + 4, then click on the line with the red ! at the start)
At the bottom of the file that appears, there should be a line that says something like:
1. While emitting IR SIL function #_TToZFC4Down8Resource12getInstancesfMS0_U__FTSS6paramsGVSs10DictionarySSPSs9AnyObject__9onSuccessGSqFGSaQ__T__7onErrorGSqFT5errorCSo7NSError8responseGSqCSo17NSHTTPURLResponse__T___T_ for 'getInstances' at /path/to/file.swift:112:5
The location where your error occurred is at the end of that line. (In this case, on line 112 of file.swift in getInstances).
I was trying to add the PayPal framework to my iOS Project (Xcode 7.2 and Objective C language). When building it did not throw any error, but when I tried to archive the Project and make the IPA, I was getting that error
unable to execute command: Segmentation fault: 11
Screenshot:
After struggling for a long time, I disabled the Bitcode in Project's Target > Build Settings > Enable Bitcode. Now the project can be archived. Please check the following screenshot.
Can't really give a straight solution on this (although I'm sure it's an Apple bug), but I just came across the exact same error message and happen to solve it. Here's what I did:
In General
Comment out recently changed Swift code (check commits) until the app compiles again
Command-click each called method in the failing line and check if there could be an ambiguity
My Example
In my case (I was using the XMPPFramework written in Objective-C) the failing code looked like this:
for roomMessage: XMPPRoomMessage in self.messages {
let slices = split(roomMessage.nickname(), { $0 == "_" }, allowEmptySlices: false)
}
Once I replaced roomMessage.nickname() with "0_test" the code didn't fail any more. So I command-clicked the method nickname() (twice) and here's what I saw:
My guess was that the Swift 1.1 compiler has problems with figuring out which method to call if the exact type of an object is not clear. So I made the type of roomMessage explicit and got another error which I fixed by removing the braces behind the nickname() method call. This made my app build again. Here's the working code:
for roomMessage: XMPPRoomMessageCoreDataStorageObject in self.messages {
let slices = split(roomMessage.nickname, { $0 == "_" }, allowEmptySlices: false)
}
I hope this helps someone out there to investigate the issue more quickly than I did.
I also had the same problem,
when I cleaned the derived data
Remove all removed derived data from Trash as well.
Stop Xcode, restart it and clean build
It should be fixed now.
In my case this error because I use Class name for variable
var MYClass : MYClass {
get {
return.....
}
}
And this fixes my problem
var myClass : MYClass {
get {
return.....
}
}
My problem was that I tried to mimic static variables with the so-called module approach (the Module design pattern). So, I had something like that (just a simple static reference to an operation queue declared at the level of a swift file):
let globalQueue: NSOperationQueue = {
let queue = NSOperationQueue()
queue.suspended = false
queue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount
return queue
}()
So, that worked fine in Xcode 6.x.x, but ceased to compile in Xcode 7beta. Just want you guys to be aware of it.
P.S. In general, I managed to find out what was wrong from the logs (see the screenshot attached). Hope this saves you some time.
I got Segmentation fault when I called a protocol function the same protocols extension.
I had a code something in the line with this:
protocol Rotatable {
func rotate() -> Self
}
extension Rotatable {
func rotate(steps: Int) {
for _ 0..<steps { self.rotate() }
}
}
When I later made an object and declared that it would follow the Rotatable protocol I got Segmentation fault 11 and the program crashed.
Ex: this would cause Segmentation fault and crash Xcode
struct SomeStruct : Rotatable {
}
If I however first implemented the function rotate() in SomeStruct and then afterwards declared that it conformed to Rotatable there where no problem.
I had a similar today and tried the steps described here including removing files I had recently modified. Nothing seemed to work. I tried something that had been suggested when SourceKit would crash in Xcode.
I when into the derived data directory and deleted everything. The location is listed under "Preferences -> Locations -> Derived Data" There is an arrow icon right next to the path which opens finder with that directory selected. Select all the directories inside and delete them. Close Xcode and Reopen it. That made the problem disappear for me.
I think that some intermediate file is getting corrupted and the compiler does not know how to handle it.
I get this error because a silly mistake!!
in a class I defined
var url: String!?
:)
So it seems that this description is a multiple & generic error for a lot of reasons!!
This can happen as well if you are porting Objective-C code to Swift and you move an objective C protocol to swift. If you leave off the #objc at the protocol definition and you still have Objective-C code that uses that protocol you can get this error.
The solution in that case is adding #objc to the protocol
protocol MyPortedProtocol {}
changes to
#obcj protocol MyPortedProtocol {}
Also make sure any classes that implement this protocol add #objc to the methods
I did answer in "Swift compiler segmentation fault when building"
I had this error too, and i fixed like this:
check your project and find out which files are using twice and remove one, or delete all and re-add them.
Errors in my xCode
:0: error: filename "AttributedString.swift" used twice: '/Users/.../CNJOB/CNJOB/AttributedString.swift' and '/Users/.../CNJOB/CNJOB/AttributedString.swift'
:0: note: filenames are used to distinguish private declarations with the same name
:0: error: filename "APIClient.swift" used twice: '/Users/.../CNJOB/CNJOB/APIClient.swift' and '/Users/.../CNJOB/CNJOB/APIClient.swift'
:0: note: filenames are used to distinguish private declarations with the same name
Command /Applications/Xcode 3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
For me it's caused by adding the swift files to different targets (today extension in my case).
I forgot to add one #end after #implementation in a .m file that had multiple classes in it. Something like:
#implementation Adjust
#end
#implementation Data //#end For this class was missing
#implementation Create
#end
I got this bug because of line
self.textView.inputAccessoryView = self.toolbarItems;
If you delete it the error will gone.
My steps:
1)
Deleted Derived data
Cleared build folder Didn't help
Copied class files to another folder as backup and commented everything in this class. Error gone.
Commented code blocks one by one until
build was success.
For me the problem was mixing Generics, Extensions, and #objc.
It turns out Xcode doesn't like having #objc inside extensions of generic classes:
class FaultyClass<T: TypeValidator>: UIControl where T.ItemType == String {
}
extension FaultyClass: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
}
}
The above code gives the error #objc is not supported within extensions of generic classes. So I moved the method to the class itself but didn't delete the empty extension. This got rid of the error but when I compiled the project I got the segmentation fault.
The solution was to move UITextFieldDelegate to the class declaration.
class GoodClass: <T: TypeValidator>: UIControl, UITextFieldDelegate where T.ItemType == String {
// MARK: - TextFieldDelegate
func textFieldDidEndEditing(_ textField: UITextField) {
}
}
My problem was in methods signatures:
func setCategory(categoryId: Int?, subcategoryId: Int?) -> FilterSettings {
func changeCategory(categoryId: Int?, subcategoryId: Int?, handler: #escaping (Int) -> ()) {
I don't get why compiler cannot handle such declarations.
In my case it was because of an inappropriate inout in the function parameters. So I suggest you to look for that as well.
For me it was something similar to what #LuisCien described in this answer https://stackoverflow.com/a/42803582/4075379
I didn't have any generics or #objc tags, but it was these lines of code that were causing the segmentation fault:
public extension CGFloat {
/// Whether this number is between `other - tolerance` and `other + tolerance`
func isEqual(to other: CGFloat, tolerance: CGFloat) -> Bool {
return (other - tolerance...other + tolerance).contains(self)
}
}
i.e. an extension on a primarily Objective-C primary type?
Very luckily, I was able to delete those lines because the project wasn't using anymore. That fixed the issue.
Dumb mistake. I referred to self in a Class method:
public class func FunctionName() -> UIImage {
let bundle = Bundle.init(for: type(of: self))
...
}
I run into this problem when building some legacy code whaich was not adapted for latest Swift versions.
Segmentation fault: 11
When you open Report navigator it contains some context like:
1. Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)
2. While evaluating request IRGenSourceFileRequest(IR Generation for file "/Users/alex/Downloads/NSURLProtocolExample-Swift_complete/NSURLProtocolExample/AppDelegate.swift")
3. While emitting IR SIL function "#$s20NSURLProtocolExample11AppDelegateC11applicationAD29didFinishLaunchingWithOptionsSbSo13UIApplicationC_So12NSDictionaryCSgtF".
for 'application(application:didFinishLaunchingWithOptions:)' (at /Users/alex/Downloads/NSURLProtocolExample-Swift_complete/NSURLProtocolExample/AppDelegate.swift:17:3)
0 swift 0x000000010b2d3615 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 37
1 swift 0x000000010b2d2615 llvm::sys::RunSignalHandlers() + 85
2 swift 0x000000010b2d3bcf SignalHandler(int) + 111
3 libsystem_platform.dylib 0x00007fff2039bd7d _sigtramp + 29
...
To solve this issue:
comment the pointed line (line 17 in AppDelegate.swift)
Build and fix all others issues
uncomment line from step 1
Swift 5 Very Easy And Smooth Solution
1- Just check your last added Extension / Code / Folder File before then this issue occur
2- Just Commit the code or save that code
3- Clean and Build & DONE :-)
Happy Coding
I ran into a similar problem when switching from beta2 to beta4.
Clean
then
Build

Resources