spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » SWIFT » Page 1
Swift Closure Single Statement Issue
Single statement body in a closure have implicit return, so what happens is that the compiler tries to set the result of this statement: self?.popOverView.center = gesture.locationInView(self?.view) as the return value. You can fix that by adding an explicit return self?.popOverView.center = gesture.locationInView(self?.view) return This happens for single statements only, that's why it work

Categories : Swift

satisfying if statement with all nodes of enumerateChildNodesWithName
You should update a boolean variable in the enumeration loop and check the outcome after all nodes have been enumerated: var allVelocitiesAreZero = true orbLayer.enumerateChildNodesWithName("player", usingBlock: { node, stop in // ... if (orb.physicsBody?.velocity.dx != 0 || orb.physicsBody?.velocity.dy != 0) { allVelocitiesAreZero = false stop.memory = true } }) if a

Categories : Swift

How do I get the count of a Swift enum?
I have a blog post that goes into more detail on this, but as long as your enum's raw type is an integer, you can add a count this way: enum Reindeer: Int { case Dasher, Dancer, Prancer, Vixen, Comet, Cupid, Donner, Blitzen case Rudolph static let count: Int = { var max: Int = 0 while let _ = Reindeer(rawValue: max) { max += 1 } return max }() }

Categories : Swift

unexpectedly found nil while unwrapping an Optional value with AVAudioPlayer
It looks like AVAudioPlayer hasn't been audited yet. It returns an implicitly unwrapped optional, which can be nil, and apparently is on your iPad. (Likely because your iPad doesn't know where /Users/Dan/Documents/... is, since that's on your computer.) You want to capture the player in an optional value so you can test for nil before you use it: var sound = NSURL(fileURLWithPath:"/Users/Dan/Doc

Categories : Swift

Moving a sprite in the update function Swift
You can define a global variable (or an array if you have more sprites) var label: SKLabelNode? In your create method you can assign the new sprite to the variable func createLabel() { label = SKLabelNode() ... } Now you can manipulate the label in your update method func update() { label.DoSomething... .... }

Categories : Swift

Swift & Parse.com find by specific column not ID
Why are you querying the database for a username and password. Adding a new user is very simple with Parse. Taken directly from their docs: Query User table on Parse You can query the user table first, using a PFQuery: PFQuery *query = [PFUser query]; [query whereKey:@"username" equalTo:username]; Adding New User The idea of user accounts that let people access their information and share

Categories : Swift

Swift Take a Variable
You need to implement prepareForSegue where you have access to the destination view controller. Here is an example on how to do that: class ViewController: UIViewController { @IBOutlet var newButton: UIButton! @IBAction func goToSecondView(sender: AnyObject) { self.performSegueWithIdentifier("goToSecondView", sender: self) } override func prepareForSegue(segue: UIStorybo

Categories : Swift

Alamofire doing two requests
Is your loginViewFetchedUserInfo() function inside a UIViewController? Maybe you are initializing this UIViewController or the owner class of the function twice. In my case this was caused because of many instances of the same class using the same Notification Observer name.

Categories : Swift

Can't dismiss keyboard, UITextField delegate being called OK
You are returning 'false' from 'textFieldShouldEndEditing'. The following is an excerpt from the 'UITextFieldDelegate' documentation: Return Value YES if editing should stop; otherwise, NO if the editing session should continue Discussion This method is called when the text field is asked to resign the first responder status. This might occur when your application asks the t

Categories : Swift

overload gestureRecognizerShouldBegin with UIPanGestureRecognizer in swift
Remove override, and don't forget to add the UIGestureRecognizerDelegate extension. You can add it at the bottom of your class class YourViewController: UIViewController { // You class declaration } extension YourViewController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { // return true } }

Categories : Swift

Swift -- How to create UIAlertView button click or response
Two things: You shouldn't exit from an app. The user will hit the Home button when they are done with your app. If you call exit(0), that is a crash as far as the user is concerned. Alerts don't block. Your if will happen before the user has had a chance to respond to your alert. You need to make your ViewController a UIAlertViewDelegate: class ViewController: UIViewController, UIAlertViewD

Categories : Swift

Swift: HighScore / NSUserDefaults
Steve's answer in that related question does not use NSUserDefaults at all, and instead he is archiving & retrieving the high score from a "highScore.archive" file store in your app's Document directory. Any solution you come up with should forget about user defaults and instead rely on your HighScore object that you instantiate (which loads and saves into that highScore.archive file).

Categories : Swift

Using edgeLoopFromRect in Swift
You should first define a bitmask category to represent the physics body of your game scene. I typically use the 32-bit binary value 00000000000000000000000000000001, which I define as a constant: let SCENE_EDGE_CATEGORY: UInt32 = 0x1 With that constant defined, you can now define the scene's physics body in a very readable way: self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame) se

Categories : Swift

UIGesture Recognizer Crashes Application
The ":" in "handleSwipe:" indicates that method handleSwipe takes an argument. In this case, a gesture object is passed to the gesture handler. So, your function should be func handleSwipe(gesture:UISwipeGestureRecognizer) { println("Swiped Right") }

Categories : Swift

Animate SCNBox height by keeping base in the same y
Yes, you're correct that the pivot is what you need to change. The pivot is a transform — meaning it can encompass scaling and rotation for setting the "base" orientation of a node — but all you need is a translation. To anchor the box at the bottom, translate the pivot by half the box's height: boxNode.pivot = SCNMatrix4MakeTranslation(0, -(box.height/2), 0) However, this isn't enough to k

Categories : Swift

Swift implement multiple protocols with a delegate
In your code, delegate is just a normal property. You can have multiple protocols declaring a property with the same name and same type, and have a class directly or indirectly implement it. If different protocols define a property with the same name but different type, you won't be able to make it compile, because the compiler will complain for redeclaration of a property and class not confirmi

Categories : Swift

Swift: No such module "GoogleMaps" error
The steps on that website are still for Objective-C apps. To write an app in Swift with the Google Maps API, you need to add a bridging header, and then you can import the module in that header using #import <GoogleMaps/GoogleMaps.h>. In application:didFinishLaunchingWithOptions: instead of using [GMSServices provideAPIKey:@"API_KEY"]; then you use GMSServices.provideAPIKey("API_KEY").

Categories : Swift

How to set velocity in Swift
From Apple's SpriteKit documentation: A Boolean value that indicates whether the physics body is moved by the physics simulation. Declaration Swift var dynamic: Bool Objective-C @property(nonatomic, getter=isDynamic) BOOL dynamic Discussion If the value is NO, the physics body ignores all forces and impulses applied to it. This property is ignored on edge-bas

Categories : Swift

Capitalizing first char of sentence (Swift)
import Foundation // A lowercase string let description = "the quick brown fox jumps over the lazy dog." // The start index is the first letter let first = description.startIndex // The rest of the string goes from the position after the first letter // to the end. let rest = advance(first,1)..<description.endIndex // Glue these two ranges together, with the first uppercased, and you'll //

Categories : Swift

Conditionally lifting protocols to generic types in Swift
You can't do this in Swift, since you can't further constrain a generic type. For example, you can't add methods to Array<T> that only work when T is Comparable - that's why there are so many global functions for dealing with generic types (map, filter, sort, etc.). From a recent Chris Lattner posts in the dev forums, it sounds like the Swift developers are headed in this direction, but it'

Categories : Swift

Swift change color of NavigationControl and TabBar
try this in your firstViewController class ViewController: UIViewController,UITabBarDelegate, UITabBarControllerDelegate, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() UITabBar.appearance().tintColor = UIColor.redColor() var view: UITableView = self.tabBarController?.moreNavigationController.topViewController.view

Categories : Swift

Accessing function in MasterViewController from DetailViewController (swift)
Use an optional. var masterViewController: MasterViewController? Optionals do not have to be initialized when the class is created. In prepareForSegue() assign the pointer as usual: destinationViewController.masterViewController = self Then when you need to call removeLocation: masterViewController?.removeLocation("London")

Categories : Swift

how to init a UIButton subclass?
Two things you need there -- (1) cvstPosition need an initial value, either in the declaration or in the init before you call super.init(). (2) That call to fatalError is put in so you don't forget to implement the initializer -- it's basically an on-purpose crash. Delete! Setting initial value in the declaration, no need for an init: class CVSTButton : UIButton { var cvstPosition: Double =

Categories : Swift

Is it OK to Move Common ViewController Presentation Logic into Presentation Helper Classes
I know too little about your problem to provide the definite answer, but basically you have 2 options: - inheritance - composition I personally like inheritance although it is often stated you should choose composition over inheritance. Your helper sounds somewhat like composition, so that would be the preferred setup. With your specific problem as I understand it, inheritance would lead to a

Categories : Swift

Swift out of bounds array loop / catching exceptions?
You are removing items from your collections as you are iterating over them. Don't do that. Instead, you could collect the indices you want to remove in an array, and then remove them in reverse order (from largest to smallest) after you are done with the loops above.

Categories : Swift

Background Image node interfering with touch command
Here's an example of how to allow a user to drag and drop a node: let background = SKSpriteNode(color:SKColor.blueColor(),size:CGSizeMake(200, 200)) let player = SKSpriteNode(color: SKColor.whiteColor(), size: CGSizeMake(32, 32)) var selectedNode:SKNode? override func didMoveToView(view: SKView) { let point = CGPointMake (CGRectGetWidth(view.frame)/2,CGRectGetHeight(view.frame)/2) backgr

Categories : Swift

"'C' is not identical to 'UInt8'" in Swift when using += operator
No, += is a separate operator, so you have to add it to your protocol definition: protocol Concatenable { func +(lhs: Self, rhs: Self) -> Self func +=(inout lhs: Self, rhs: Self) init() } The Swift error messages can be misleading. Perhaps the compiler tries to use any known += definition, e.g. func +=(inout lhs: UInt8, rhs: UInt8) by converting the arguments to UInt8. Note t

Categories : Swift

"IR generation failure: program too clever" in Swift
I had the same problem, where I extended an Array with a protocol that also conformed to CollectionType. I believe that the error occurred because Swift saw that Array was being asked to conform to two protocols with the same name, but wasn't clever enough to work out that they were the same protocol. I've just downloaded the latest version of Xcode (6.3) with the latest version of Swift (1.2) an

Categories : Swift

Can't modify multidimensional array using .last
last returns the last element, but it doesn't allow you to set a new value. In fact the property implements the get only: /// The last element, or `nil` if the array is empty var last: T? { get } So you cannot use it to modify the array. Note that in case the returned element is a composite value type (i.e. a struct, like an array or a dictionary), a copy of the actual element stored in the ar

Categories : Swift

Swift syntax for GKMatchmaker.matchForInvite
I know this is an old question but I just came across it and thought i'd offer my two cents. this is how i implemented that function GKMatchmaker.sharedMatchmaker().matchForInvite(invite, completionHandler: { (match: GKMatch!, error: NSError!) -> Void in if error != nil { // error out } if match != nil { // success } })

Categories : Swift

How do I add a downloaded custom font to a navigationBar title in Swift?
Be sure your font is in Bundle Resources. For some reason Xcode it is not importing custom font properly most of the time: and try this in the AppDelegate UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "JennaSue", size: 20)!, NSForegroundColorAttributeName : uicolorFromHex(0x5C8CA7)]

Categories : Swift

Definition for swift annotated apis
Essentially, Apple is having to go through all their APIs and annotate each function with information about the allocation of memory for parameters and return values. Once that's done, annotated functions can be used from within Swift more easily, since the compiler knows what it has to do to safely bridge types back and forth from Swift code to annotated C code. Here's an example of similar anno

Categories : Swift

ios Swift AES Encrypt and Decrypt
I found the solution, it is a good library. Cross platform 256bit AES encryption / decryption. This project contains the implementation of 256 bit AES encryption which works on all the platforms (C#, iOS, Android). One of the key objective is to make AES work on all the platforms with simple implementation. Platforms Supported: iOS , Android , Windows (C#). https://github.com/Pakhee/Cross-pl

Categories : Swift

Implementing StringLiteralConvertible on NSURL in Swift 1.1
The initializers required by the protocol "StringLiteralConvertible" do not return optionals, so putting a ? after init won't help (even though XCode itself suggests it). But all initializers for NSURL do return optionals, because the parameters may not result in a valid URL. And you have to call one of the super.init initializers in all custom NSURL initializers. So it is no longer possible to ha

Categories : Swift

Entered CLLocationDegrees value yields erroneous value. Why?
Looks like a problem with the debugger. As Martin notes, it works fine with println(): let lat : CLLocationDegrees = -37 let long : CLLocationDegrees = 144 println("Lat: (lat) Long: (long)") // Output: "Lat: -37.0 Long: 144.0" I'd file a radar against lldb.

Categories : Swift

How to accept Game Center invite in swift
Finally I have figured out the solution which works. I had to implement the GKLocalPlayerListener like this and call the match for invite within the delegate function. func player(player: GKPlayer!, didAcceptInvite invite: GKInvite!) { GKMatchmaker.sharedMatchmaker().matchForInvite (invite, {(InvitedMatch, error) in if InvitedMatch != nil { myMatch=InvitedMatch

Categories : Swift

What does this two question mark mean?
It's the coalescing operator. It returns the first expression (featureImageSizeOptional) if it's non-nil. If the first expression is nil, the operator returns the second expression (CGSizeZero). See the Language Guide for more info.

Categories : Swift

How to disable external access to a property?
Use the private attribute: class Test { private var myVariable = 2 } There are 3 access levels: public: accessible to all internal: accessible in the current module only private: accessible from any code in the same file If no modifier is specified, it is defaulted to internal More info: Access Control

Categories : Swift

Adding TapGestureRecognizer to UILabel in Swift
It looks like you've declared klikPlay as a nested function inside didMoveToView: override func didMoveToView(view: SKView) { // ... let tapGesture = UITapGestureRecognizer(target: self, action: "klikPlay:") func klikPlay(sender:UITapGestureRecognizer){ // ... } } You need it as an instance method of your class for the gesture recognizer to find it properly: class MyVi

Categories : Swift


Recently Add
App crashes on segue after embedding view controllers
Swift Closure Single Statement Issue
satisfying if statement with all nodes of enumerateChildNodesWithName
How do I get the count of a Swift enum?
unexpectedly found nil while unwrapping an Optional value with AVAudioPlayer
Moving a sprite in the update function Swift
Swift & Parse.com find by specific column not ID
Swift Take a Variable
Alamofire doing two requests
Can't dismiss keyboard, UITextField delegate being called OK
overload gestureRecognizerShouldBegin with UIPanGestureRecognizer in swift
Swift -- How to create UIAlertView button click or response
Swift: HighScore / NSUserDefaults
Using edgeLoopFromRect in Swift
UIGesture Recognizer Crashes Application
Animate SCNBox height by keeping base in the same y
Swift implement multiple protocols with a delegate
Swift: No such module "GoogleMaps" error
How to set velocity in Swift
Capitalizing first char of sentence (Swift)
Conditionally lifting protocols to generic types in Swift
Swift change color of NavigationControl and TabBar
Accessing function in MasterViewController from DetailViewController (swift)
how to init a UIButton subclass?
Is it OK to Move Common ViewController Presentation Logic into Presentation Helper Classes
Swift out of bounds array loop / catching exceptions?
Background Image node interfering with touch command
"'C' is not identical to 'UInt8'" in Swift when using += operator
"IR generation failure: program too clever" in Swift
Can't modify multidimensional array using .last
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.