windowNibName error in Swift / Cocoa? - swift

Well, that will teach me to set down Swift programming for a year and a half. Apparently things have changed.
In my past programs, this inside my MainWindowController was quite happy:
class MainWindowController: NSWindowController {
override var windowNibName: String? {
return "MainWindowController"
}
...
But now I'm getting this error:
Property 'windowNibName' with type 'String?' cannot override a
property with type 'NSNib.Name?'
I've been Googling and poking around Stack Overflow but have been unable to figure out what the exact problem is and how to fix it. What has changed over the last year and a half in this regard? Ideas would be most welcome.
Thanks in advance!

Now type of windowNibName replace to struct from String.
You can check more details here.
To fix error you can use below code :
class MainWindowController: NSWindowController {
override var windowNibName: NSNib.Name? {
return NSNib.Name("MainWindowController")
}
}
If -initWithWindowNibPath:owner: was used to initialize the instance, this gives the last path component with its extension
stripped off. If -initWithWindowNibName:[owner:] was used this just
gives that name.
open var windowNibName: NSNib.Name? { get }

Related

How to convert String to Int in Swift?

There has been same titles of this question but different situations.
In this case this is very simple but I can't find a same problem online.
So here's the code
class ViewController: UIViewController {
#IBOutlet weak var fldTotalUnits: UITextField!
var intTotalUnits:Int? = Int(fldTotalUnits)
The error here says "Cannot use instance member 'fldTotalUnits' within property initializer;..."
I tried replacing var with let, I tried NSString, I tried .toInt() but nothign worked... so how do I this?
String to Int conversion is not complicated. You simply do the conversion at the wrong place. You are trying to reference one member in the initialization of another member, that is not allowed. In this particular case simply because fldTotalUnits has the value nil when you would try to use it via Int(fldTotalUnits). When creating an instance of your class ViewController fldTotalUnits is set to nil and initialized with a useful value later. Therefore what you have to do in the first place is move the line into a separate method:
func doSomething() {
var intTotalUnits:Int? = Int(fldTotalUnits)
}
Now you will see that the compiler complains about there not being a suitable initializer because you have to access the text property of fldTotalUnits instead of using the actual textfield:
func doSomething() {
var intTotalUnits:Int? = Int(fldTotalUnits.text!)
}
Now you can think about moving the declaration of intTotalUnits to somewhere else, but setting its value has to happen in some method.
The code in your question is trying to create an Int from a UITextField, not a String. What you should say is something like…
var intTotalUnits:Int?
func updateTotalUnits()
guard let text = fldTotalUnits.text else { return }
intTotalUnits = Int(text)
}

Command failed due to signal: Segmentation fault: 11 while emitting IR SIL function

I want to add closure properties in the extension of UITextView so I define a closure using typealias:
typealias TextViewHeightDidChangedClosure = (_ currentTextViewHeight:CGFloat)->Void
extension UITextView{
func setTextViewHeightDidChanged(textViewHeightDidChanged:TextViewHeightDidChangedBlock){
objc_setAssociatedObject(self, &TextViewHeightDidChangedBlockKey, textViewHeightDidChanged, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
func textViewHeightDidChanged()->TextViewHeightDidChangedBlock?{
let textChanged : ((CGFloat)->Void) = objc_getAssociatedObject(self, &TextViewHeightDidChangedBlockKey) as! TextViewHeightDidChangedBlock
return textChanged
}
}
But it tells me an error that says:
Command failed due to signal: Segmentation fault: 11.
Here is an image of the error
Can anyone tell me why and give me an deep meaningful explanation, thank you very much!
You can also have this error if you declare a Bool! property in a class and you try to make a ternary condition with this property:
var isSomething: Bool!
func myFunc() {
let value = isSomething ? "something" : "not"
}
Just add the ! on your property
var isSomething: Bool!
func myFunc() {
let value = isSomething! ? "something" : "not"
}
Generally, crashing with SegFault 11 is a bug of compiler and you'd better send a bug report.
And most such bugs can be worked around with fixing your code properly.
The most significantly bad thing in your code is that usual closures in Swift (#convention(swift) -- usually omitted) cannot be passed to Any which represents id of Objective-C. Use #convention(block) which is stated as id-compatible in the Swift book (this part):
typealias TextViewHeightDidChangedBlock = #convention(block) (_ currentTextViewHeight:CGFloat)->Void
You may have tried this, but in this case, just putting #convention(block) does not solve the issue.
It seems another trick is needed to make your code work, explicitly cast to AnyObject:
extension UITextView{
func setTextViewHeightDidChanged(textViewHeightDidChanged: #escaping TextViewHeightDidChangedBlock){
objc_setAssociatedObject(self, &TextViewHeightDidChangedBlockKey, textViewHeightDidChanged as! AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
func textViewHeightDidChanged()->TextViewHeightDidChangedBlock?{
let textChanged : ((CGFloat)->Void) = objc_getAssociatedObject(self, &TextViewHeightDidChangedBlockKey) as! TextViewHeightDidChangedBlock
return textChanged
}
}
So, this seems to be a flaw of id-as-Any. Any which represents id should accept id-compatible closure.
I'm not sure Apple would fix this bug soon, but anyway, as far as I tested, my code above worked as expected.
For me it was because I was declaring protocols for two extensions on a generic class and implementing them in the class declaration. I am using xCode 9 swift 4
I faced the similar issue in Xcode 9.3, I opened the given swift class as mentioned in error image(mine was differ), went to method(mention in error) there was code like below
class func makeViewCircular(view: AnyObject) {
let viewCircle = view
viewCircle.layer.cornerRadius = view.frame.size.width/2
viewCircle.layer.borderColor = UIColor.clear.cgColor
viewCircle.layer.borderWidth = 1.0
}
So, I edit the code to like below. Fixed the problem. The problem was with the AnyObject type. I typecast AnyObject to UIView.
class func makeViewCircular(view: AnyObject) {
if let viewCircle = view as? UIView{
viewCircle.layer.cornerRadius = view.frame.size.width/2
viewCircle.layer.borderColor = UIColor.clear.cgColor
viewCircle.layer.borderWidth = 1.0
}
}
In my case, the swift class I am referring in Objective-C is missing #objc. I was using #class in my .h file and referring the swift class in header file. Might help someone as the error doesn't gives any clue about this.

Xcode6.3.2 Swift bug with static constants

I am trying to figure out why I am having constant compile problems with this type of construct in Xcode 6.3.2.
class Foo {
static let CONSTANT_NAME = "CONSTANT_STRING"
...
func bar () -> String {
var s = String(format:"%s,%d\n", CONSTANT_NAME, 7)
return s
}
...
}
As I understand the language, this should be perfectly legal code however Xcode is constantly (hah-pun) having issues with it raising the error
"there is no member CONSTANT_NAME in class Foo"
If I get lucky and force it to clean, and then rebuild it will some times sort itself out and work. Other times, even doing that, then trying an open/close project will still not resolve the issue.
So, I guess my implicit follow up question (if the answer to the above is - it is legal code) is: is the Xcode Swift compiler that buggy that even basic things like this are likely to cause problems? If so, swift seems to be in a pretty bad state.
static is class property, that means you have to call it like this ClassName.property
class Foo {
static let CONSTANT_NAME = "CONSTANT_STRING"
func bar () -> String {
var s = String(format:"%s,%d\n", Foo.CONSTANT_NAME, 7)
return s
}
}
That is not a bug. That is what it should be. A class property "belongs" to the class.
If you want your code work without using ClassName, do not use static
class Foo {
let CONSTANT_NAME = "CONSTANT_STRING"
func bar () -> String {
var s = String(format:"%s,%d\n",CONSTANT_NAME, 7)
return s
}
}
More details in the Apple Documentation
The static let syntax is legal and valid. The issue is that you must fully qualify that variable when you access it:
var s = String(format:"%s,%d\n", Foo.CONSTANT_NAME, 7)
The compiler error is a bit obtuse, but it is telling the truth... CONSTANT_NAME is not a member, but a type property of class Foo: Swift Type Properties
I hear you about saving key strokes. I've personally been trying to make my Swift code as idiomatic as possible by milking every short cuts but when you find code like this, you should be glad that the compiler asks you to keep on the safe side:
class Foo {
static let CONSTANT = "hello"
func bar() -> String {
let CONSTANT = "bye"
return CONSTANT // I know which one! Thanks Swift!
}
}
println(Foo.CONSTANT)
println(Foo().bar())

Checking for optional protocol methods in Swift gives error?

After reading the Apple docs on optional protocol requirements it says you can use optional chaining to check for the implementation. I tried this out and I keep getting an error. It seems like this is no longer a valid way of doing this and I am trying to find out if there is a new way to do this now.
Here is a example so you can see the error: http://swiftstub.com/743693493/
Here is my code:
#objc protocol Bearable {
func growl()
optional func cough() -> String //Apparently bears cough when they are scared.
}
#objc class Bear:Bearable {
var name = "Black Bear"
func growl() {
println("Growllll!!!")
}
}
#objc class Forest {
var bear:Bear?
func scareBears() {
if let cough = bear?.cough?() {
println(cough)
} else {
println("bear was scared")
}
}
}
I get the error: error: 'Bear' does not have a member named 'cough'
if let cough = bear?.cough?() {
The error you're getting makes sense because Swift can know at compile time that Bear doesn't implement cough() (whereas Objective-C wouldn't necessarily be able to know that).
To make your code compile, you need to define bear using the Bearable protocol instead of the Bear class.
var bear: Bearable?
Which is probably what you'd want anyway. Otherwise, there's not much point in creating that protocol.

Swift compiler segmentation fault when building

Adding a (convenient) computed height property to UIView in my UIViewExtension.swift file is causing the Swift compiler to segfault... What could possibly be going wrong here?
0 swift 0x00000001061e5608 llvm::sys::PrintStackTrace(__sFILE*) + 40
1 swift 0x00000001061e5af4 SignalHandler(int) + 452
2 libsystem_platform.dylib 0x00007fff894da5aa _sigtramp + 26
3 libsystem_platform.dylib 0xb03939841e997c88 _sigtramp + 2504775416
4 swift 0x00000001064c8bb9 swift::NominalTypeDecl::getMembers(bool) const + 41
5 swift 0x00000001055efab9 swift::irgen::ClassMetadataLayout<(anonymous namespace)::FindClassMethodIndex>::addClassMembers(swift::ClassDecl*) + 329
6 swift 0x00000001055e97b2 swift::irgen::emitVirtualMethodValue(swift::irgen::IRGenFunction&, llvm::Value*, swift::SILType, swift::SILDeclRef, swift::CanTypeWrapper<swift::SILFunctionType>, swift::ResilienceExpansion) + 434
7 swift 0x00000001056550d3 swift::SILVisitor<(anonymous namespace)::IRGenSILFunction, void>::visit(swift::ValueBase*) + 42611
8 swift 0x000000010564a266 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 8678
9 swift 0x00000001055cb6f8 swift::irgen::IRGenModule::emitGlobalTopLevel() + 184
10 swift 0x00000001056376e3 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1859
11 swift 0x0000000105638033 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
12 swift 0x00000001055aa65a frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 4842
13 swift 0x00000001055a935d main + 1533
14 libdyld.dylib 0x00007fff8a82e5fd start + 1
 
1. While emitting IR SIL function #_TFCSo6UIViewg6heightSd for 'anonname=0x7ff422892fd0' at <path redacted>/UIViewExtension.swift:60:5
<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)
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254
If more information is needed to crack this, just comment. Thanks!
Edit:
Here's a related .xcodeproj that returns this question's compiler error. Download here
I had this error because I was doing this :
if(currentMeal?.State == .Deleted){
}
instead of
if(currentMeal!.State == .Deleted){
}
so I think optional not unwrapped in if condition can cause this error
When you run into a compiler segfault in Swift, you don't get a handy line number and error message. Here's how you can track the problem down:
Create a new file called SegFaultDebugger.swift in your project.
In this new file, define an extension to the class that's giving you problems.
Move a group of methods from the main file to SegFaultDebugger.swift.
Compile.
At this point, one of three things happens:
You still get the segfault in the original file: Move the methods from SegFaultDebugger.swift back to the original file and move a different set of methods into SegFaultDebugger.swift. Repeat
You get a segfault in SegFaultDebugger.swift: Great! Now use binary search to pin the segfault down to a specific method until you can figure out what construct is causing it.
You get meaningful compiler errors: Great! Fix the errors. Once everything compiles, move your methods back into the original file.
I got this error while extending one of my protocols and mistyped and optional type argument.
protocol SomeProtocolName: class {
var someProtocolVariable: String { get set }
func someProtocolFunction(someProtocolVariable: String)
}
// MARK:
extension SomeProtocolName {
func someProtocolFunction(someProtocolVariable: String?) {
self.someProtocolVariable = someProtocolVariable
}
}
The difference in function arguments String in prototype and String? in extension caused Segmentation Fault 11.
In Xcode 7, you can click on the error in the Debug Navigator and you'll be shown an expanded view of the crashes. Clicking on the hamburger button on the right expands the error, and if you scroll all the way down to the bottom of the expanded error message, you will see where it comes from.
For me, I had two of those segmentation fault errors. In the picture above, the first one is what it looks like when collapsed, the second is when you expand the hamburger button. At the very bottom of the expanded gray box, you'll see a message that says where the compiler crashed.
Note however that the error message may at times be not informative enough, so while it tells you where it crashed, it doesn't always say why and how to fix it. Getting rid of this error is still very much a matter of guesswork.
I had this error too, and I fixed it like this:
Check your project and find out which files are used twice and remove one, or delete and re-add them all.
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
I’ve discovered a simple workaround until the problem is fixed in a future Xcode/Swift build:
Simply place all extensions causing the issue in the .swift file that it’s being used.
In the example project you provided, place the contents of UIViewExtension.swift and CALayerExtension.swift above AppDelegate.swift
Hopefully this can get us to write working Swift code until the problem’s cleared up.
As for me, adding private to static var fixed clang crash:
private static var taskId = 0
I had a compiler segmentation fault on a statement like this:
someFunction(isFlagged ? "String1" : "String2")
I just did a if-else statement instead and it works.
This typically happens when the compiler does not have enough information (despite what you think) to guarantee/determine the state of a statement or a variable within a statement.
For example, imagine you have a dictionary of type [String: String] which you populate with city names as keys and a comma separated list of corresponding zip codes/post codes.
Imagine that somewhere in your code you want to update the list of corresponding codes:
myDict[town] += newZipCode + ","
In this case, the compiler will respond with segmentation fault as town might not be in the dictionary and therefore it cannot guarantee that the above statement will have a valid value.
To resolve this, you should store the current state of myDict[town] in a separate variable allowing you to handle the case of key not in dict and then update the value for the given key:
myDict[town] = guaranteedValue + "," newZipCode + ","
Unfortunately, it is not always straightforward to determine the root cause so I hope this simple example helps.
You can also have this problem if you declare a condition with an unwrapped Bool as a property
In my case, a misplaced colon during string interpolation broke mine (XCode 6.1.1).
Example:
println("\(value1:value2)")
when I meant to do:
println("\(value1) : \(value2)")
This error happened to me when I tried to override weak variable from parent class.
In base class:
weak var stripeViewDelegate : StripeViewDelegate? = nil
Derived class:
override weak var stripeViewDelegate : StripeViewDelegate? = nil {
didSet {
self.stripeView.delegate = stripeViewDelegate
}
The error disappeared when I removed =nil from derived class.
I catch some exception today
class func createByAny(instance: Any?) -> ApiCollectionResponse { ... }
and this solved it:
class func createByAny(instance: Any) -> ApiCollectionResponse { ... }
Because "Any" type is any type event "nil", "AnyObject", optional, ... :)
It is cannot be optional, it is already optional.
typealias Any = protocol<>
This error happens also if you accidentally declare a variable with a type matching its name:
var sectionGroup: sectionGroup? { ... }
Ran into this error because of an extraneous generic type on an operator function, e.g.
func ==<T>(lhs: Foo, rhs: Foo) -> Bool {
return lhs.bar == rhs.bar
}
In my case, removing <T> resolved the issue.
In my case I had declared a struct inside a func. Moving the struct to class level solved the issue.
Now that I write this I remember having had issues with struct inside funcs before. It was something else than the segmentation fault (which seems to become notorious with the Swift 1.2 beta). OMG Apple, what are you doing there?
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.....
}
}
Im my case, this happened when I did incorrect static initialization in a protocol. I found a way to get around, but a compiler should never produce a segmentation fault while building.
There are three files involved. A protocol NamedSegues.swift, a custom TableViewController that among other things implements the protocol which contains a callback, a custom TableViewCell that holds reference to this protocol to call the callback.
//file1
import Foundation
protocol NamedSegues {
func executeSegueWithId(id: String) -> Void
static func getDefault() -> NamedSegues // This was required because of init requirement in CustomCellView
}
//file2
class CustomController: UITableViewController, NamedSegues {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCellID", forIndexPath: indexPath ) as! CustomCellView
// Configure the cell...
//App logic...
cell.parent = self
}
//Mark: NamedSegues
func executeSegueWithId(id: String) ->() {
NSLog("Received callback to execute segue: \(id)")
//
}
static func getDefault() -> NamedSegues { // I think this must be where it threw up.
return self as! NamedSegues
}
}
//file3
import UIKit
class CustomCellView: UITableViewCell {
var id: String = "NoName"
var parent: NamedSegues = NamedSegues.getDefault() // This is where it was needed.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
NSLog("Touched id: \(id)")
parent.executeSegueWithId(id) // This is where parent was used.
}
}
I got around it by using ?
In the protocol file, file1: delete the declaration of getDefault()
In the CustomController file2: delete the implementation of getDefault.
In the CustomCellView, file3:
var parent: NamedSegues?
...
parent?.executeSegueWithId(id)
The compiler should have caught this and given some error message instead of throwing a segmentation fault during build!
Seems like the Swift 2 compiler might not have been quite ready for prime-time! In case this helps anyone, I was getting a segmentation fault: 11 due to a mismatch with the variable type in a closure header, specifically in a Parse method, PFQuery.query.findObjectsInBackgroundWithBlock.
You can see the issue in more detail here:
https://github.com/ParsePlatform/Parse-SDK-iOS-OSX/issues/280
Like #Fjohn said, this was an issue related to unwrapping an optional for me (broke in both Xcode 7.0 beta 6 and Xcode 7). In my case, I was not unwrapping optional of the optional (what tipped me off was double ?? in the descriptor. Using if let solved the issue
As others wrote above, for me this happened when I'm using an extension over a protocol but the signature of methods in the protocol don't match the implementations in an extension.
In my case, I had added a new parameter to the implementation (in the extension) but forgot to also add it to the method's signature in the protocol.
in my case, I tried to add a function parameter after a variadic parameter.
Reversing parameter sequence and making the variadic parameter the last parameter in the parameter list fixed it.
Swift 3.0 (Xcode 8.1) exhibits this issue when a protocol declares an optional variable, and an implementer implements that variable as a lazy initialised one.
Bug is reported here:
https://bugs.swift.org/browse/SR-1825
Xcode 8.2.
Adding #nonobjc protocol implementation into extension causing segmentation faults.
Move #nonobjc protocol implementation into class implementation.
In my case the culprit was accidentally overloading a function expecting an array argument with one with a variadic argument:
public required init(_ args: Node...) {
}
When the superclass had it defined as an array:
public required init(_ args: [Node]) {
}
For me the following caused a segfault while type is an optional:
switch type {
case .aType:
// Do Something
default:
break
}
and this solved it:
switch type {
case .Some(.aType):
// Do Something
default:
break
}
I got this error with the following method signature in a custom UITableViewController.
func filterContentForSearchText(searchText: String)
changing to:
func filterContentForSearchText(searchText: String!)
fixed the problem.
I had the same problem in an extension. My extension had two convenience initializers:
convenience init(context: NSManagedObjectContext) {
let entityDescription = NSEntityDescription.entityForName("PropertyEntity", inManagedObjectContext: context)!
self.init(entity: entityDescription, insertIntoManagedObjectContext: context)
}
convenience init(dictionary: NSDictionary, context: NSManagedObjectContext) {
self.init(context: context)
property1 = (dictionary["key"] as? String) ?? ""
// More properties...
}
To get rid of the error I added an instance method map(dictionary: NSDictionary) and the segmentation fault error disappeared.
convenience init(dictionary: NSDictionary, context: NSManagedObjectContext) {
self.init(context: context)
map(dictionary)
}
For me the issue was having my architectures not set to the standard. I had added i386 or something, just set it back to default xcodeproject arch and it compiled fine.
I had the same problem in a swift project. The issue was a function that should have returned an object, but didn't have a return in it. This sort of error used to be signaled while editing with Obj-C. It seems like t isn't the case in Swift.