FAQ Database Discussion Community


print function in swift 2.0

swift,swift2
In swift 2.0, print() automatically adds a newline character. In swift 1.2, println() and print() used to be separate functions. So how do I print some text and not add a newline to it since swift no longer has a print function that does not append newlines.

Swift 2 ( executeFetchRequest ) : error handling

swift,swift2
I got some issue with the code that I can't figure out. After I installed Xcode 7 beta and convert my swift code to Swift 2 Code: override func viewDidAppear(animated: Bool) { let AppDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let Context: NSManagedObjectContext = AppDel.managedObjectContext let request = NSFetchRequest(entityName: "PlayerList") List...

Call can throw, but errors can not be thrown out of a global variable initializer

swift,swift2
I'm using Xcode 7 beta and after migrating to Swift 2 I experienced some issues with this line of code: let recorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as! [String : AnyObject]) I get an error saying "Call can throw, but errors can not be thrown out of a global variable...

Swift do-try-catch syntax

swift,swift2
I give it a try to understand new error handling thing in swift 2. Here is what I did: I first declared an error enum: enum SandwichError: ErrorType { case NotMe case DoItYourself } And then I declared a method that throws an error (not an exception folks. It is...

Swift 2.0 replicate OBJC_ASSOCIATION_RETAIN

swift,objective-c-runtime,swift2
I'm extending some classes in Swift 2.0 to work with ReactiveCocoa 3.0 (swift-2.0 branch), but have run into some trouble. I've followed Colin Eberhardt's tutorial, and have copy pasted some of his UIKit extension logic over to my OS X app. It all compiles fine, apart from this property: UInt(OBJC_ASSOCIATION_RETAIN),...

String indices in Swift 2

xcode,swift,swift-playground,swift2
I decided to learn Swift and I decided to start with Swift 2 right away. So here is an very basic example that's similar to one of the examples from Apple's own e-book about Swift let greeting = "Guten Tag" for index in indices(greeting) { print(greeting[index]) } I tried this...

Xcode 7 beta – differences in NSDateComponents?

xcode,swift,calendar,swift2
I have been working on a clock app in Swift and with Xcode 6.3.2 the following code builds and runs just fine. // Get current time let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitNanosecond, fromDate: date) let hour = components.hour...

No back button on segue in Swift 2

ios,swift,segue,swift2,ios9
I just ported my project over to Swift 2, and everything is working great - except that even the most simple segues have no back button. Here is the prepare for segue function that I am using: override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller...

NSObject class conforms to protocol contained in NSArray with Swift

swift,nsarray,protocols,swift2,swift-array
I would like to create a method in Swift that returns an array of NSObject objects that conform to a protocol. I've tried something like this: func createManagers() -> [Manager] { let result = NSMutableArray(capacity: self.classes.count) (self.classes as NSArray).enumerateObjectsUsingBlock { (object: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in //...

In Swift 2, how can I return JSON parsing errors to the completion block?

try-catch,swift2
I would like to create a function in Swift 2 that gets data from a URL and returns it as a JSON object using NSURLSession. At first, this seemed pretty straight forward. I wrote the following: func getJson(url:NSURL, completeWith: (AnyObject?,NSURLResponse?,NSError?)->Void) -> NSURLSessionTask? { let session = NSURLSession.sharedSession() let task =...

Swift 2 Error handling and while

swift,swift2
For example following code: while let data = Provider.getData() { ... } With Swift 2 you get two errors: Initializer for conditional binding must have Optional type, not 'String' Call can throw, but it is not marked with 'try' and the error is not handled. What is the best solution...

Display an UIAlertView when app launches

swift,swift2
I'm trying to add a UIAlertView or Controller when the app first loads. Currently, I have this code in my viewDidLoad method. let welcomeAlert = UIAlertController(title: "hola", message: "this is a test.", preferredStyle: UIAlertControllerStyle.Alert) welcomeAlert.addAction(UIAlertAction(title: "ok.", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(welcomeAlert, animated: true, completion: nil) Why won't the alert view...

Fixing NSURLConnection Deprecation from Swift 1.2 to 2.0

swift,xcode7,swift2,ios9
I have a function written in Swift 1.2, that checks for Reachability of Address or IP. Here it is : func isHostConnected(hostAddress : String) -> Bool { var response : NSURLResponse? let request = NSMutableURLRequest(URL: NSURL(string: hostAddress)!) request.timeoutInterval = 3 let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) return ((response...

Change what print(Object) displays in Swift 2.0

swift,printing,swift2
I am trying to make my class Digit display the num variable whenever print is called on that object, in Swift 2.0. I thought this might be done with a description variable, but no luck. class Digit { var num: Int var x: Int var y: Int var box: Int...

Swift 2.0 Errors

xcode,build-error,swift2
I am trying to use the following code: func redrawShape(shape: Shape, completion:() -> ()) { for (idx, block) in shape.blocks.enumerate() { let sprite = block.sprite! let moveTo = pointForColumn(block.column, row: block.row) let moveToAction: SKAction = SKAction.moveTo(moveTo, duration: 0.05) moveToAction.timingMode = .EaseOut sprite.runAction(moveToAction, completion: nil) } I get an error at...

Xcode 7 run on Mac OSX 10.10 Yosemite

swift,osx-yosemite,swift2,xcode7,osx-elcapitan
Am I missing something or Xcode 7 should run only on new(beta) OSX 10.11 El Capitan? I downloaded beta and after some code changes to comply with Swift 2.0 my project compiles and runs fine under OSX 10.10.3. Am I missing something or Apple changed the game somehow?...

Swift 2.0 - Binary Operator “|” cannot be applied to two UIUserNotificationType operands

ios,swift,swift2
I am trying to register my application for local notifications this way: UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil)) In Xcode 7 and Swift 2.0 - I get error Binary Operator "|" cannot be applied to two UIUserNotificationType operands. Please help me....

Var init in do-catch

swift,swift2
Following code: // Setup components do { let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) let deviceInput = try AVCaptureDeviceInput(device: captureDevice) let output = AVCaptureMetadataOutput() let session = AVCaptureSession() } catch { return false } After this you can't access the initialized variables. The error is "Use of unresolved identifier" if I want to...

UIAlertView deprecated in iOS 9, How to update code?

ios,xcode,swift,swift2,xcode7
I have the current line of code in one of apps, it is a simple UIAlertView. However with the new Swift 2.0 update on various other updates apple has made, this is now deprecated. let alertView = UIAlertView(title: "Oops!", message: "This feature isn't available right now", delegate: self, cancelButtonTitle: "OK")...

TabBarController instance Swift 2.0

ios,tabbarcontroller,swift2
I am trying to Compile my app again now that Swift 2 is out and the thing is I am having an error with TabBarController instances. I am declaring the instances in vars in order to use methods from anothers ViewControllers. Here it's my code: let barViewControllers = self.tabBarController?.viewControllers let...

Xcode 7.0 Swift Update Problems

xcode,swift2
I'm trying to update my project to work with Xcode 7.0 and after updating my Swift projects I'm getting an error that I don't understand on this line. let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary The error is "Call can throw, but it is not marked with 'try' and...

After installing Xcode 7, Xcode 6.3 shows errors about converting to Swift 2

xcode,swift,swift2,xcode7
After installing Xcode 7 to play with Swift 2 in Playgrounds, I've got a weird problem: when I open an existing Xcode 6.3 project with Xcode 6.3, it throws lots of errors about conversions to Swift 2. This project was just cloned from the repository and hasn't been opened with...

How to create enum from a String

swift,enums,swift2
In Swift 2, can you create an enum from a string? enum Food : Int { case Pizza, Pancakes } let str = "Pizza" let food = Food(name:str) // for example That last line doesn't work, but I'm looking for something like it. Like in Java, you can say Food.valueOf("Pizza")....

What is the difference between Swift 2.0 do-try-catch and regular Java/C#/C++ exceptions

swift,error-handling,runtime-error,swift2
It seems that Swift 2.0 has changed from traditional ObjC (NSError returning) and Swift 1.X (Success/Failure optionals) conventions of runtime error handling, to something that looks very similar to exception handling in languages like Java/C#/C++/etc. Apple has traditionally emphasized use of NSError instead of throwing NSException for runtime errors (vs...

Changes to registerUserNotificationSettings in Swift 2?

swift,uilocalnotification,swift2
I can't seem to find any documentation on registerUserNotificationSettings beyond what was produced last November (here), but my old code doesn't seem to work for me any more in Xcode 7 and Swift 2. I have this code in App Delegate: let endGameAction = UIMutableUserNotificationAction() endGameAction.identifier = "END_GAME" endGameAction.title =...

Convert Character to Int in Swift 2.0

swift,int,character,swift-playground,swift2
I just want to convert a character into an Int. This should be simple. But I haven't found the previous answers helpful. There is always some error. Perhaps it is because I'm trying it in Swift 2.0. for i in (unsolved.characters) { fileLines += String(i).toInt() print(i) } ...

Binary operator '|' cannot be applied to two UIViewAutoresizing operands

ios,swift,cocoa-touch,swift2
Getting this error in Swift 2.0. Binary operator '|' cannot be applied to two UIViewAutoresizing operands Here is the code: let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568)) addSubview(view) view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight Any idea what can be the problem? ...

How to use NSRegularExpression in Swift 2.0?

ios,swift,swift2
I have written this function in String Extension and can't figure out the error. func isEmail() -> Bool { let regex = NSRegularExpression(pattern: "^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,4}$", options: [.CaseInsensitive]) return regex.firstMatchInString(self, options: nil, range: NSMakeRange(0, characters.count)) != nil } The error is: Call can throw, but it is not marked with 'try' and...

withUnsafePointer in Swift 2

swift,swift2
I'm trying to check if the user has internet connection, and part of the process involves invoking withUnsafePointer. In Swift 1.x, I was able to use: var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))...

Swift 2 : NSData(contentsOfURL:url) returning nil

ios,json,xcode,foundation,swift2
I have a webpage address which contains a JSON file. I'm trying to access the JSON file as NSDictionary in Swift 2. Every time I call NSData(contentsOfURL:url!) where url is type of NSURL?, it returns nil. I'm using Xcode 7 Beta, and the project was first made in Xcode 6....

Swift 2 NSURLSession.sharedSession().dataTaskWithURL Cannot invoke with an argument list of type

swift2,xcode7
Cant seem to get the following code to compile with Xcode 7, I get error "Cannot invoke 'dataTaskWithURL' with an argument list of type" Looks like completionHandler is no longer optional, cant figure out how to rewrite the following code. Any help appreciated, Thanks let session = NSURLSession.sharedSession() let url...

Swift 2 - UnsafeMutablePointer to object

swift,pointers,swift2
If I have a method like: func someMethod(contextPtr: UnsafeMutablePointer<Void>) how do I get the object from the contextPtr? func someMethod(contextPtr: UnsafeMutablePointer<Void>){ let object:MyObject = contextPtr.memory } gives: 'Void' is not convertible to 'MyObject' What's the secret sauce More detail: What I'm actually doing here is setting up a global callback...

Swift 2.0 : Cannot invoke with an argument list of type… (HTTP Request)

swift,swift2
Since I upgraded to Xcode 7 beta I have an error that I can't fix. Here's the full code from my DataManager.swift import Foundation var TopAppURL:String = String() var numberAsked:String = String() class DataManager { class func getInfo(ID : String){ TopAppURL = "http://sweetapi.com/?=\(ID)" numberAsked = ID } class func loadDataFromURL(url:...

Swift 2.0 : 'enumerate' is unavailable: call the 'enumerate()' method on the sequence

swift,swift2
Just downloaded Xcode 7 Beta, and come up with this error on enumerate keyword. for (index, string) in enumerate(mySwiftStringArray) { } Can anyone help me overcome this ? Also, seems like count() is no longer working for counting length of String. let stringLength = count(myString) On above line, compiler says...

Update button image on swift 2.0

ios,uibutton,swift2,xcode7
When I try using this solution to update an UIButton image (Xcode 7 beta 1), it gives me this error: "Cannot invoke 'setImage' with an argument list of type '(UIImage?, forState: nil)'" Here's the code: if counter % 2 == 0{ playButton.setImage(UIImage(named: "pause"), forState: nil) } else if counter %...

openMapsWithItems cannot Invoke with argument list issue in Swift 2.0

swift,apple-maps,swift2
I'm having a few issues converting my Swift 1.2 code to 2.0 - this is one of those issues. I have a function which opens the iOS Maps app to give directions to a location. It was working fine until the conversion. Now I get the following error message: Cannot...

Server Authentication in Swift 2.0 & XCode 7 broken

ios,swift,ssl,swift2
I just updated my code to Swift 2.0 to work with Xcode 7. My App performs NSURLAuthenticationMethodServerTrust and NSURLAuthenticationMethodClientCertificate authentication. The problem is NSURLAuthenticationMethodServerTrust authentication stopped working on my simulator - but still works on my test device with iOS 8.3. Besides my old project which is not Swift 2.0,...

'Convert to latest Swift Syntax' breaks the build even when there are no changes

swift,swift2
My project is in objective-c with just one tableviewcontroller in swift. I downloaded the Xcode-beta today which prompted me to 'Convert to latest Swift Syntax'. After I follow the steps it shows me that there are no changes. I do not see any changes in the proj file either but...

Binary operator '&&' cannot be applied to two Bool operands [duplicate]

beta,swift2,xcode7
This question already has an answer here: Swift 2 migration saveContext() in appDelegate 2 answers I recently updated Xcode to the new 7.0 beta. I did the migration with the assistant but there are a few more issues. func saveContext () { if let moc = self.managedObjectContext { var...

Calling Swift from C

c,xcode,swift,swift2
I have seen many articles explaining how to call C functions from Swift, but I would like to explore the converse (if possible), to call Swift functions from C. I have seen examples illustrating Swift functions in objC, but these do not get me any closer to my goal. Is...

“Variable 'xxx' was never mutated; consider changing to 'let' constant” ERROR

swift2,xcode7
I have the following problem. I use this code below and I get the issue "Variable 'characteristic' was never mutated; consider changing to 'let' constant" for var characteristic:CBCharacteristic in service.characteristics ?? [] { print(str) _selectedPeripheral!.writeValue(str.dataUsingEncoding(NSUTF8StringEncoding)!, forCharacteristic: characteristic, type: CBCharacteristicWriteType.WithoutResponse) } When I change to "let", there's an Error: 'let' pattern...

iOS 9 not opening Instagram app with URL SCHEME

ios,swift,swift2,ios9
The following URL opens on iOS 8.3 and lower, but it does not work and iOS 9 let instagramURL = NSURL(string: "instagram://app") Why won't the URL open?...

Looping through a dictionary and checking each value type

swift,loops,dictionary,swift2
How do I loop through a dictionary and check for each items value type? Example dictionary: var dict = ([ "a number" : 1, "a boolean" : false, "a string" : "Hello" ]) My attempts at checking for values: for item in dict.1 { if let current = item as?...

Use NSSerialization.datawithJSON in swift

swift2
Been trying to get this to work in swift 2.0 , the error says "Type NSJSONWritingOptions cannot conform to protocol NilLiteralConvertible" at var options = prettyP........ func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String{ var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil if NSJSONSerialization.isValidJSONObject(value) { do{ let data = try NSJSONSerialization.dataWithJSONObject(value,...

do try in beginSheetModalForWindow

swift,error-handling,swift2
In Swift 2.0, If I do the following: panel.beginSheetModalForWindow(self.view.window!) { (result) in switch result { // Save was selected case NSFileHandlingPanelOKButton: self.writeFile(fileString, fileURL: panel.URL!) // something else was selected default: break } } With a function as follows, it compiles and works. func writeFile(fileString: String, fileURL: NSURL) { do {...

Int is not convertible to UIInterfaceOrientationMak for supportedInterfaceOrientations()

swift,int,uiinterfaceorientation,swift2,xcode7
I have another problem with Xcode 7. I have tried some research but cannot come up with a solution. The error is Int is not convertible to UIInterfaceOrientationMask. The code below: override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if visibleViewController is KINWebBrowserViewController { return Int(UIInterfaceOrientationMask.All.rawValue) } return Int(UIInterfaceOrientationMask.Portrait.rawValue) } Thanks...

How to make a segue from SpriteKit GameScene to UIViewController programmatically in iOS 9 with Swift2

sprite-kit,segue,identifier,swift2,ios9
I need to make a segue from a GameScene to a UIViewController but i keep getting Use of unresolved identifier "push" although I did give it that identifier In the GameSceneViewController I added scene.viewController = self and in my GameScene I added var viewController: UIViewController? and func segue(){ self.viewController.performSegueWithIdentifier(push, sender:...

Linking error when building Parse in Xcode 7

swift,parse.com,ios9,xcode7,swift2
I am trying to add the Parse.com SDK to my Xcode 7 project. I have followed the getting started guide and I have managed to do it before in Xcode 6. However this time I am being shown this error message when I try to build: ld: framework not found...

Swift 2 : OBJC_ASSOCIATION_RETAIN_NONATOMIC use of unresolved identifier

objective-c,swift2
I just updated my project to Swift 2. I one of my swift class I use ObjC association. I have the following : objc_AssociationPolicy( OBJC_ASSOCIATION_RETAIN_NONATOMIC) Since the update, the compiler returns Use of unresolved identifier 'OBJC_ASSOCIATION_RETAIN_NONATOMIC'. Any idea why ? Edit: For those who have the same problem, a temporary...

Swift 2 migration saveContext() in appDelegate

swift,swift2
I have just downloaded the new Xcode 7.0 beta and did a migration from Swift 1.2 to Swift 2. The migration apparently did not change the whole code, in fact a method saveContext() which was fine until throws 2 errors for the line: if moc.hasChanges && !moc.save() { Binary operator...

Override func error in Swift 2

swift,swift2
This code in XCode 6 does not have error but in XCode 7 (Swift 2) this error has occurred : Method does not override any method from its superclass override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { /* Called when a touch begins */ } When remove override word this...

Check for internet conncetion in Swift 2 (iOS 9)

ios,xcode,swift,reachability,swift2
When I try to check for an internet connection on my iPhone by using Swift 2 in xCode I get a bunch of errors. Can anyone help me to fix this? The code: import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress =...

SpriteKit remembering which sprite was touched

swift,sprite-kit,touch,swift2
I have a 'game' with 3 sprites. If a user clicks 'Sprite1', and thereafter 'Sprite2'. Is there some way to remember which sprites were pressed? Its only for 2 sprites if there are more i will need to empty the 'memory' and start over with the last one 'touched', i...

Making code not runnable on other platforms

swift2,availability
In Swift 2, how can I use the #available condition to prevent a block of code from executing on a certain platform? The * seems to allow the version you specify in your deployment target. And specifying iOS Int.max doesn't work.

Cannot subscript a value of type '[String]' with an index of type 'Int'

ios,xcode,swift,swift2,xcode7
I'm recently trying to build a custom UITableViewCell Class by adding a minor improved UITextField. I am also coding in swift 2 and I realised this error by recompiling the project in Xcode 7 beta. I initialised the array by call a custom init method. Heres is my Code: INIT...

startAccelerometerUpdatesToQueue Type of expression is ambiguous without more context

swift,core-motion,swift2
I am trying to translate the following code to Swift 2. manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) { [weak self] (data: CMAccelerometerData!, error: NSError!) in self!.outputAccData(data.acceleration) } But this gives me the following error. Type of expression is ambiguous without more context Does anyone know why this is happening?...

Error when using reduce() in Swift 2.0

function,swift,reduce,swift2
When I attempt to use the reduce function, I get an error saying: reduce is unavailable: call the 'reduce()' method on the sequence I already figured out how to do this with the enumerate() function but I cannot seem to solve this issue. Here is the line of code returning...

Selecting global or object function

swift,cocoa,swift2
I am working with on a Cocoa project in Swift and confronted the following problem: Several classes in the Cocoa Framework (such as NSWindow or NSView) implements a function called print: that opens a window in order to print something (don't really know what), so when I work within a...

Swift 2 guard keyword

swift2,guard-statement
Swift 2 introduces the guard keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates an submitTapped function: func submitTapped() { guard username.text.characters.count > 0 else { return } print("All good") } I am wondering if using...

can't use contains in swift2 using xcode 7

contains,swift2
I am using swift2. I used this code: while contains(currentCardValues, randomNumber + 1){ I am getting this error: "contains" is unavailable: call the 'contains() method on the sequence ' ...

How to declare recursive enums with Swift 2.0

ios,xcode,swift,swift2
I'm trying to experiment with recursive enums in Swift 2 however I'm getting compilation errors. I started off trying to define my own example: enum Tree { case Empty indirect case Node(value: Int, left: Tree, right: Tree) } But get an error: "Consecutive declarations on a line must be separated...

Iterate through a String Swift 2.0

swift,swift-playground,swift2,xcode7
I am trying to do a very simple piece of code in Swift playgrounds. var word = "Zebra" for i in word { print(i) } However, I always get an error on line 3. 'String' does not have a member named 'Generator' Any ideas on why this doesn't work? Note:...

Swift 2 - Pattern matching in “if”

swift,if-statement,syntax,pattern-matching,swift2
Recently I've saw the WWDC 2015 keynote from Apple. I also looked at some documentation but I can't find a "pattern matching in if" section, how it was written on one of the slides which they have shown. (73min 00sec video from Apple Events) Do you know what's this refers...

'Module was not compiled for testing' when using @testable

ios,swift,unit-testing,swift2
I'm trying to use Swift 2's new @testable declaration to expose my classes to the test target. However I'm getting this compiler error: "Intervals" is the module that contains the classes I'm trying to expose. How do I get rid of this error?...