How to set CMutablePointerObjCBool to false in Swift?
This is the equivalent of *stop = YES;
:
stop.withUnsafePointer { $0.memory = true }
To make it more succinct, you could do things like:
operator infix <- {}
@infix func <- <T>(ptr: CMutablePointer<T>, value: T) {
ptr.withUnsafePointer { $0.memory = value }
}
and then the line above becomes simply this:
stop <- true
Not sure if that's recommended style, though...
(You can choose characters from / = - + * % < > ! & | ^ . ~
to create custom operators.)
How to stop enumerateObjectsUsingBlock Swift
In Swift 1:
stop.withUnsafePointer { p in p.memory = true }
In Swift 2:
stop.memory = true
In Swift 3 - 4:
stop.pointee = true
How to use enumerateChildNodesWithName with Swift in SpriteKit?
For now, don't trust autocomplete to insert the code you need — it drops in signatures from the "header", but a block signature is not the same as the declaration you need when inserting your own closure for a block parameter.
The formal way to write a closure would be to replicate the signature inside braces, adding local parameter names and using the in
keyword to mark the start of the closure body:
self.enumerateChildNodesWithName("enemy", usingBlock: {
(node: SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in
// do something with node or stop
})
But Swift's type inference means you don't have to write that much. Instead, you can just name the parameters, because their type (as well as the closure's return type) is known:
self.enumerateChildNodesWithName("enemy", usingBlock: {
node, stop in
// do something with node or stop
})
You can also use trailing closure syntax:
self.enumerateChildNodesWithName("enemy") {
node, stop in
// do something with node or stop
}
(You can even drop the local parameter names and refer to parameters by position — e.g. $0
for node
— but here isn't a great place to do that because it makes your code far less readable. It's best to reserve $0
and friends for closures where it's blindingly obvious what the parameters are, like the closures you use with map
and sort
.)
See Closures in The Swift Programming Language for further explanation.
Also, because stop
is an UnsafeMutablePointer
, the syntax for using it is a bit different than in ObjC: set stop.memory = true
to break out of enumeration.
How to use indexesOfObjectsPassingTest: in Swift
This code is working in the Playground for me ;) Hope it helps a bit
Extra Function-Definition
import Cocoa
let list = [2, 3, 4, 5, 6, 7, 8]
func test (object: AnyObject!, index: Int, stop: CMutablePointer<ObjCBool>) -> Bool
{
let number = object as Int
return (number % 2 == 0) //for even numbers
}
let result: NSIndexSet = (list as NSArray).indexesOfObjectsPassingTest(test)
println("\(result.lastIndex)") //prints "6" (because 8%2=0)
Inline-Closure
I transformed my above example to work with an inline-closure (described in the Swift-eBook). The parameter-list and return-type is separated by the term in
.
import Cocoa
let list = [2, 3, 4, 5, 6, 7, 8]
let result: NSIndexSet = (list as NSArray).indexesOfObjectsPassingTest({
(object: AnyObject!, index: Int, stop: CMutablePointer<ObjCBool>) -> Bool in
let number = object as Int
return (number % 2 == 0) //for even numbers
})
println("\(result.lastIndex)") //prints "6" (because 8%2=0)
.enumerateGroupsWithTypes block stop parameter Swift (Xcode 6 beta 5)
NSLog("Error!", nil)
is wrong and should be NSLog("Error!")
.
(This seems to confuse the Swift compiler and causes unrelated error messages.)
How should I decide if my func should return optional or implicitly unwrapped optional?
It's probably too early to have strict best practices for swift, but here's my opinion. In general implicitly unwrapped optionals should be used for a few cases such as outlets, properties that are nil until initialization and return values from Objective-C functions, otherwise a regular optional should be used.
If you are creating a function that will return a value or nil, do the other programmers interacting with your code a favor and make the return value an optional.
enumerateObjectsUsingBlock in Swift
Foundation
enumerateObjectsUsingBlock:
is not a method on Array but on NSArray. If you want to use it you'll need an instance of NSArray rather than Array.
import Foundation
var array: NSArray = ["Some", "strings", "in", "an", "array"]
array.enumerateObjectsUsingBlock({ object, index, stop in
//your code
})
if you have an existing array, you can cast a swift Array
to an NSArray
using as
var cocoaArray = swiftArray as NSArray
or if you simply import Foundation
the Swift compiler will automatically bridge your Swift array to an NSArray and all the NSArray methods will become available for you.
Swift 1
or you can just use Swift's enumerate
function:
for (index, value) in enumerate(array) {
// your code
}
Swift 2
In Swift 2, enumerate
is no longer a free function, now it's in a protocol extension!
for (index, value) in array.enumerate() {
// your code
}
Swift 3
And in Swift 3, enumerate
was renamed to enumerated
for (index, value) in array.enumerated() {
// your code
}
Get a list of nodes in an specific area?
You are creating a physical world where there is a specific rectangle that has 'special properties' - this is the rectangle that you use in enumerateBodiesInRect()
. Why not create an invisible, inert physical body with the required rectangular dimension and then use SKPhysicsBody
to check for collisions and/or contacts? You could then use allContactedBodies()
or some delegate callbacks to learn what other bodies are inside your special rectangle.
Think of it like a 'tractor beam' or a 'warp rectangle'.
Related Topics
Adding Custom Game Logic to Scene Kit (Swift)
Programmatically Set Uipageviewcontroller Transition Style to Scroll
How to Send Different Users to Separate View Controllers Using Firebase and Xcode
Creating Tableview Sections from JSON Data Swift 4
Avcapturesession and Avaudiosession Recording Video While Background Music Playing Only Works Once
How to Get Label Name from Button
How to Perform Realm Count Query
Segue Out of Navigation Controller
Why Doesn't iOS System Sound Play in Simulator
Xcode 12.5 Missing Entitlement Com.Apple.Developer.Associated-Appclip-App-Identifiers
How to Check If Device Orientation Is Landscape Left or Right in Swift
Timer Label Not Updated After Switching Views (Swift)
How to Create a Ntlm Authentication Header to Use with Alamofire
Changing Font Size in a Label for Only iPhone 4S, Is This Possible
Incorrect Position of Cashapelayer
How to Convert an Int into Nsdata in Swift
Double Tap Necessary to Select Tableview Item with Search Bar