Attempting to store to property '' within its own willSet - ios

Im getting a weird warning in the editor which I need help understanding what it wants
Attempting to store to property 'someProperty' within its own willSet, which is about to be overwritten by the new value
var someProperty:SomeClass! {
willSet { someProperty?.someFunction() } // Get warning: Attempting to store to property 'someProperty' within its own willSet, which is about to be overwritten by the new value
didSet { ... }
}
When I run it it is doing what I want it to do with no crashes or warnings in console, so I see this as just a false positive. So can I suppress it in any way because its annoying? :(

This is a known bug, reported in the Apple Developer Forum: https://devforums.apple.com/message/1065306#1065306, with the workaround
of adding an explicit self:
willSet {
self.someProperty?.someFunction()
}
Update: I could not reproduce the issue with Xcode 7.3.1 or Xcode 8
anymore, so that seems to be fixed now.

Related

Realm crash on iOS 10 with 'String'

I have recently released a new version of our app and during beta testing, it's crashing on all iOS 10 devices but not other versions. Since we have Crashlytics, we found a strange crash message in the backend that we can confirm is the reason all iOS 10 crashing since it's 100% iOS 10 and there's like 40 of them.
It reads as follows:
Fatal Exception: RLMException
Property Article.id is declared as String, which is not a supported managed Object property type. If it is not supposed to be a managed property, either add it to ignoredProperties() or do not declare it as #objc dynamic. See https://realm.io/docs/swift/latest/api/Classes/Object.html for more information.
And here's the object:
class Article: Object {
#objc dynamic var id: String = UUID().uuidString
// others...
override static func primaryKey() -> String? {
return "id"
}
}
As you can see, this is perfectly nomral and runs fine on other iOS. In Realm's doc, it LITERALLY SAYS to use String with #objc dynamic and there's no way it's unsupported. I suspect there's nothing special about Article.id, and since Article starts with A, it happens to be the first String property of all realm Objects. Maybe somehow all Strings stopped working on iOS 10?
Can anyone offer some advice or insights?(Please don't say things like drop iOS 10 support. For now, we need it.)
We ran into the same issue a couple of times, trying to drag Realm fully into Swift. This is not really the answer but more of a workaround we've had success with when needing backward compatibility.
It's an ObjC object, not Swift.
There's something going on with the bridging, perhaps conforming to NSCopy'ing or something along those line, so just change it to read
#objc dynamic var id = NSUUID().uuidString
See the Getting Started Guide in the Models section which calls for using NSUUID
NSUUID: An object representing a universally unique value that bridges
to UUID; use NSUUID when you need reference semantics or other
Foundation-specific behavior.
Turns out it was a Realm's bug. We happen to have another app that runs just fine on iOS 10, and after some inspection we realized that it was using Realm 4.3.2, instead of 4.4.1. After we downgraded Realm to 4.3.2, this problem disappeared.

EXC_BAD_ACCESS when trying to encode a subclass of a Codable-conformant class

I must be a moron or something but I'm scratching my head for a third day in a row and can't figure out what's going wrong with my intention to encode some JSON data in my Swift program...
Here's the situation:
I've got two classes as follows:
class Node: Codable {
// Nothing in here
}
and
class Shape: Node {
// No code here too
}
Then, I have an attempt to encode the subclass as follows:
do {
let encodedData = try JSONEncoder().encode(Shape())
} catch {
print(error)
}
This is all I have added to an empty Single View App project. When I run it, I get "Thread 1: EXC_BAD_ACCESS (code=1, address=0x350)" crash.
Of course, initially my classes used to have a lot of properties which were Codable too. I thought it was any of them, so I stripped them off but it appears it's not the properties that are causing the crash...
I'm running Xcode 9.3 on a High Sierra MacBook Pro. Is there anyone willing to reproduce this or anyone already bumped his head into such an odd behavior?
This is a known bug and you can work around it by turning on Whole Module Compilation mode for the Debug configuration, or by upgrading to Xcode 10 beta.

Swift 1.2 crashes with .lowercaseString

I have this relatively simple method for filtering a tableView's datasource objects.
func filterCategoriesWithQuery(query: String) {
placeCategoriesTableViewDataSource.filteredCategories
= placeCategoriesTableViewDataSource.placeCategories.filter({ (category: JSON) -> Bool in
let categoryName = (category["name"].stringValue).lowercaseString
if categoryName.hasPrefix(query.lowercaseString) {
return true
} else {
return false
}
})
genericTableView.reloadData()
This worked perfectly well prior to updating to Swift-1.2/Xcode-6.3b but now it always crashes when lowercaseString is utilised. It seems there's a bug with the lowercaseString method?
With NSZombieEnabled or breaking at malloc_free_break I can see that it crashes with [CFString release]: message sent to deallocated instance
Am I doing something wrong? Is this a bug? Any workarounds?
This is a bug in the first beta of Swift 1.2.
On the Apple Developer Forums, Chris Lattner mentioned a similar bug with uppercaseString that should be fixed in the next beta.
Until then, as a workaround, you can try to change the Swift compiler optimization to none in the build settings of your project. This helped me to get around a similar issue I had with an Array.

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

Swift good coding practice: If statement with optional type Bool

So I've been developing an app in Swift, and today I spent nearly an hour debugging a problem that turned out to be completely unexpected. It all resulted from the code below.
if (hero.isAI) { //isAI is a Bool
}
The problem was that this if statement ALWAYS returned true. So I thought that maybe I was setting isAI to true somewhere but in the end I realized that I declared isAI as an optional type as shown below.
var isAI: Bool!
when it should have been
var isAI: Bool
This resulted in the if-statement not checking if isAI was true, but instead checking if it contained a value.
So to be safe now I make sure to write my if-statments like this
if (hero.isAI == true) { //isAI is a Bool
}
So my question is, what are my options to avoid this problem in the future? (this problem seems extremely dangerous, especially when working on a team on a large project).
Should I always write my if-statment explicitly, should I just avoid the optional type for Bools altogether?
Note that I did not have this problem in Xcode Beta 2. This problem came about when I upgraded to Xcode beta 3. I think because in Beta 2 Apple handled implicitly unwrapped Bool in an if-statement by checking its value rather than checking if it contains a value.
Lastly, below is an example of which if-statements run given an optional Bool to better help people understand the problem.
let myBool: Bool! = false
if (myBool) {
//Runs
}
if (myBool!) {
//Won't Run
}
if (!myBool) {
//Runs
}
if (myBool == true) {
//Won't Run
}
This is a known issue that is being tracked on the SwiftInFlux repo, which includes this quote from Chris Lattner on the Apple developer forums.
This problem exists with any optional of something that conforms to
the LogicValue protocol (e.g. nested optionals, optional of bool,
etc). We consider it serious issue that needs to be fixed for 1.0 and
have some ideas, but haven't settled on a solution yet.
So, this issue doesn't just effect optional Bools, but any optional type that conforms to the LogicValue protocol (defined as).
protocol LogicValue {
func getLogicValue() -> Bool
}
Anyway as far as recommendations on how to work around this go, it's hard to recommend any one specific solution considering that Apple hasn't given an indication of how they intend to solve this in the future, but I would imagine that continuing to explicitly check the value of the Bool would be the way to go.
if (hero.isAI == true) {
// stuff
}
In fact, after some further reading, the quote listed above continues to read:
For this common case, the simplest answer would be to produce a
warning for "if x" and require someone to explictly write "if x !=
nil" or "if x == true" to make it explicit what they want.
my advice is to use this nice coalescing ??
if textfieldDate.text?.isEmpty ?? true {
// the text is either nil or empty but its all we want to know
}
If the bool is part if Core Data (aka NSNumber), you should do it like this.
if (isHero.isAI?.boolValue != nil)
Regards

Resources