MKPolygon using Swift (Missing argument for parameter 'interiorPolygons' in call) - ios7

Fellow Devs,
I'm trying to implement a polygon overlay on a mapview as follows:
private func drawOverlayForObject(object: MyStruct) {
if let coordinates: [CLLocationCoordinate2D] = object.geometry?.coordinates {
let polygon = MKPolygon(coordinates: coordinates, count: coordinates.count)
self.mapView.addOverlay(polygon)
}
}
The following error is presented:
Missing argument for parameter 'interiorPolygons' in call
According to the documentation:
Apple Docu:
Mutable Pointers
When a function is declared as taking an UnsafeMutablePointer
argument, it can accept any of the following:
nil, which is passed as a null pointer
An UnsafeMutablePointer value
An in-out expression whose operand is a stored lvalue of type Type, which is passed as the address of the lvalue
An in-out [Type] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call
Now I think that my approach then would be correct, providing a [CLLocationCoordinate2D] array. Did anyone experience the same problem and found a workaround?
thanks
Ronny

The error you're getting is Swift's cryptic way of saying that it can't find a method which matches your parameters. If you did try passing the interiorPolygons parameter, you'd get an equally confusing:
Extra argument 'interiorPolygons' in call
Your code is pretty close though; you just need a couple of minor changes. In the doc you reference, it says one of the things you can pass is:
An in-out [Type] value, which is passed as a pointer to the start of
the array, and lifetime-extended for the duration of the call
So, it's looking for an in-out parameter. Which is done by passing coordinates prefixed with an &, like so:
MKPolygon(coordinates: &coordinates, count: coordinates.count)
But, in-out parameters can't be constants. From the docs:
You can only pass a variable as the argument for an in-out parameter.
You cannot pass a constant or a literal value as the argument, because
constants and literals cannot be modified.
So, you need to define coordinates with a var first:
if var coordinates: [CLLocationCoordinate2D] = object.geometry?.coordinates
Which makes the entire function look like this:
private func drawOverlayForObject(object: MyStruct) {
if var coordinates: [CLLocationCoordinate2D] = object.geometry?.coordinates {
let polygon = MKPolygon(coordinates: &coordinates, count: coordinates.count)
self.mapView.addOverlay(polygon)
}
}

My final solution by cherry-picking from several tutorials and integrating:
func setPolylineFromPoints(locations:[CLLocation]){
if locations.count == 0 {
return;
}
// while we create the route points, we will also be calculating the bounding box of our route
// so we can easily zoom in on it.
var pt : UnsafeMutablePointer<MKMapPoint>? // Optional
pt = UnsafeMutablePointer.alloc(locations.count)
for idx in 0..<locations.count-1 {
let location = locations[idx]
let point = MKMapPointForCoordinate(location.coordinate);
pt![idx] = point;
}
self.polyline = MKPolyline(points:pt!, count:locations.count-1)
// clear the memory allocated earlier for the points
pt?.destroy()
pt?.dealloc(locations.count)
}

Related

C API with structures in Swift - immutable value as inout argument

I'm working on a Swift 3 project that involves using some C APIs that I bridged from Objective-C.
Here is a sample snippet of the structure of the API:
typedef struct
{
StructMode mode;
StructLevel level;
} TargetStruct;
typedef struct
{
. . .
TargetStruct *targetStruct;
OtherStruct *otherStruct;
NonPointerStructA nonPointerStructA;
NonPointerStructB nonPointerStructB;
. . .
} InnerStruct;
typedef struct
{
InnerStruct innerStruct;
OtherStructB otherStructB;
} OuterStruct;
In my Swift code, my goal is to set a value of the TargetStruct from the OuterStruct, like the following:
// run function that returns an instance of TargetStruct
var targetStruct: TargetStruct = initializeTargetStruct()
// assign targetStruct to outerStruct
outerStruct.innerStruct.targetStruct = &targetStruct
However, I am getting the following error:
Cannot pass immutable value of TargetStruct as inout argument
If I set a value of a struct without the *, it will work fine:
var nonPointerStructA: NonPointerStructA = initializeNonPointerStructA()
outerStruct.innerStruct.nonPointerStructA = nonPointerStructA
I have tried setting the value of targetStruct like this, but for now I have no way to test it:
var targetStruct: TargetStruct = initializeTargetStruct()
outerStruct.innerStruct.targetStruct.initialize(from: &targetStruct, count: 0)
How to solve this problem? Thank you.
In Swift, prefix & is not an address-of operator. It is just needed to clarify that some expression is passed to an inout parameter. So, your first code is syntactically invalid in Swift.
Your C-structs are imported to Swift as follows:
struct TargetStruct {
var mode: StructMode
var level: StructLevel
//some auto generated initializers...
}
struct InnerStruct {
//...
var targetStruct: UnsafeMutablePointer<TargetStruct>!
var otherStruct: UnsafeMutablePointer<OtherStruct>!
var nonPointerStructA: NonPointerStructA
var nonPointerStructB: NonPointerStructB
//some auto generated initializers...
}
struct OuterStruct {
var innerStruct: InnerStruct
var otherStructB: OtherStructB
//some auto generated initializers...
}
(If something wrong, please tell me.)
As you see, targetStruct in your InnerStruct is a pointer, and initialize(from:count:) tries to write to the pointed region, but at the time you call initialize(from:count:), targetStruct holds its initial value nil, you know what happens when dereferencing null-pointer.
One way is to allocate a memory for the TargetStruct and use the pointer to the allocated region.
func allocateAndInitializeTargetStruct() -> UnsafeMutablePointer<TargetStruct> {
let targetStructRef = UnsafeMutablePointer<TargetStruct>.allocate(capacity: 1)
targetStructRef.initialize(to: initializeTargetStruct())
return targetStructRef
}
outerStruct.innerStruct.targetStruct = allocateAndInitializeTargetStruct()
This is a more general way than below, but you need to explicitly deinitialize and deallocate the allocated region. That's sort of hard to manage.
If you can confine the usage of the outerStruct in a single code-block, you can write something like this:
var targetStruct = initializeTargetStruct()
withUnsafeMutablePointer(to: &targetStruct) {targetStructPtr in
outerStruct.innerStruct.targetStruct = targetStructPtr
//Use `outerStruct` only inside this code-block
//...
}
In this case, the pointer held in outerStruct.innerStruct.targetStruct (== targetStructPtr) is only valid inside the closure and you cannot use it outside of it.
If any of the codes above does not fit for your use case, you may need to provide more context to find the best solution.
An example of nested use of withUnsafeMutablePointer(to:_:):
var targetStruct = initializeTargetStruct()
var otherStruct = initializeOtherStruct()
withUnsafeMutablePointer(to: &targetStruct) {targetStructPtr in
withUnsafeMutablePointer(to: &otherStruct) {otherStructPtr in
outerStruct.innerStruct.targetStruct = targetStructPtr
outerStruct.innerStruct.otherStruct = otherStructPtr
//Use `outerStruct` only inside this code-block
//...
}
}
When you need more pointers to set, this nesting would be a mess, but it's the current limitation of Swift.
An example of deinitialize and deallocate:
extension InnerStruct {
func freeMemberStructs() {
if let targetStructRef = targetStruct {
targetStructRef.deinitialize()
targetStructRef.deallocate(capacity: 1)
targetStruct = nil
}
if let otherStructRef = otherStruct {
otherStructRef.deinitialize()
otherStructRef.deallocate(capacity: 1)
otherStruct = nil
}
}
}
outerStruct.innerStruct.targetStruct = allocateAndInitializeTargetStruct()
outerStruct.innerStruct.otherStruct = allocateAndInitializeOtherStruct()
// Use `outerStruct`
//...
outerStruct.innerStruct.freeMemberStructs()
The code may not seem to be too complex (just a bunch of boilerplate codes), but it's hard to find when or where to do it. As your InnerStruct may be embedded in another struct which may need to be deinitilized and deallocated...
Hope you can find your best solution.

How to rewrite this in terms of R.compose

var take = R.curry(function take(count, o) {
return R.pick(R.take(count, R.keys(o)), o);
});
This function takes count keys from an object, in the order, in which they appear. I use it to limit a dataset which was grouped.
I understand that there are placeholder arguments, like R.__, but I can't wrap my head around this particular case.
This is possible thanks to R.converge, but I don't recommend going point-free in this case.
// take :: Number -> Object -> Object
var take = R.curryN(2,
R.converge(R.pick,
R.converge(R.take,
R.nthArg(0),
R.pipe(R.nthArg(1),
R.keys)),
R.nthArg(1)));
One thing to note is that the behaviour of this function is undefined since the order of the list returned by R.keys is undefined.
I agree with #davidchambers that it is probably better not to do this points-free. This solution is a bit cleaner than that one, but is still not to my mind as nice as your original:
// take :: Number -> Object -> Object
var take = R.converge(
R.pick,
R.useWith(R.take, R.identity, R.keys),
R.nthArg(1)
);
useWith and converge are similar in that they accept a number of function parameters and pass the result of calling all but the first one into that first one. The difference is that converge passes all the parameters it receives to each one, and useWith splits them up, passing one to each function. This is the first time I've seen a use for combining them, but it seems to make sense here.
That property ordering issue is supposed to be resolved in ES6 (final draft now out!) but it's still controversial.
Update
You mention that it will take some time to figure this out. This should help at least show how it's equivalent to your original function, if not how to derive it:
var take = R.converge(
R.pick,
R.useWith(R.take, R.identity, R.keys),
R.nthArg(1)
);
// definition of `converge`
(count, obj) => R.pick(R.useWith(R.take, R.identity, R.keys)(count, obj),
R.nthArg(1)(count, obj));
// definition of `nthArg`
(count, obj) => R.pick(R.useWith(R.take, R.identity, R.keys)(count, obj), obj);
// definition of `useWith`
(count, obj) => R.pick(R.take(R.identity(count), R.keys(obj)), obj);
// definition of `identity`
(count, obj) => R.pick(R.take(count, R.keys(obj)), obj);
Update 2
As of version 18, both converge and useWith have changed to become binary. Each takes a target function and a list of helper functions. That would change the above slightly to this:
// take :: Number -> Object -> Object
var take = R.converge(R.pick, [
R.useWith(R.take, [R.identity, R.keys]),
R.nthArg(1)
]);

Trying to switch a direct integer value with a variable in swift

I'm trying to switch out a direct integer with a variable in swift, but for some reason I'm getting this error and I have no idea. The end goal is to get my currentValue (line 76) to replace the 100's on line 41 - could anyone let me know how I could accomplish this without the error? New to swift and having a hard time (background in objective-c, figured something this simple would not stop me in my tracks!)
Full .swift file here: http://pastebin.com/K6UHkNEv
EDIT:
// these values change the number of squares
let _gameView = CGOLView(gridWidth:100, gridHeight:100)
#IBOutlet weak var tileSizeSlider: UISlider!
#IBAction func sliderValueChanged(sender: UISlider) {
var currentValue = Int(sender.value)
print("\(currentValue)")
}
should work as:
// these values change the number of squares
let _gameView = CGOLView(gridWidth:currentValue, gridHeight:currentValue)
#IBOutlet weak var tileSizeSlider: UISlider!
#IBAction func sliderValueChanged(sender: UISlider) {
var currentValue = Int(sender.value)
print("\(currentValue)")
}
instead I get this error:
Use of unresolved identifier 'currentValue'
and if I try to create custom int's and input them:
var gridWidthValue = 50
var gridHeightValue = 50
like this:
let _gameView = CGOLView(gridWidth:gridWidthValue, gridHeight:gridHeightValue)
I get:
'ViewController.Type' does not have a member named 'gridHeightValue'
Any help would be appreciated - thanks stackoverflow community!
David.
currentValue is a local variable to sliderValueChanged.
Instead you should instantiate _gameView in init. Note however, you still won't be able to use currentValue.
If this is a one off sort of thing, you can always make _gameView an optional and then create it when you have adjusted the slider. This is admittedly a little clumsy.
I am not familiar with Conway's Game of Life, but looking at the code, it seems CGOLView's init does some adjustment based on the grid width and height. The reason I am mentioning this is that you could always change the view's frame size, however, you'd then also need to make some other mods to the tileViews for it to look proper.
As to why gridWidthValue/gridHeightValue is not working. Those are properties defined in an instance. Hence you would need to do somethign like self.gridWithValue to reference it. However, you cannot do that when defining the property such as
let _gameView = CGOLView(gridWidth:gridWidthValue, gridHeight:gridHeightValue)
This is also why instantiating _gameView in init is the way to go.
Your problem is that you cannot access the variable currentValue because it is inside of a function. You have to declare that value outside of the function to be able to use it outside of the function.

How to set value for CMutablePointer<MKMapPoint> in Swift

Im trying to drawn line between 2 coordinate on MKMapView and I have array for keep all poi,
So I have this code
var pointArr: CMutablePointer<MKMapPoint> = nil
and my question is how to add values to pointArr ?
You should be able to create an array of MKMapPoints and assign that to your pointer:
let lax = MKMapPointForCoordinate(CLLocation(latitude: 33.9424955, longitude: -118.4080684).coordinate)
let jfk = MKMapPointForCoordinate(CLLocation(latitude: 40.6397511, longitude: -73.7789256).coordinate)
var points: MKMapPoint[] = [lax, jfk]
let line = MKPolyline(points: &points, count: points.count)
Note that a CMutablePointer expects to point to something mutable — if points is declared with let instead of var, assigning it to a mutable pointer (or passing it to a mutable pointer parameter) won't work.
For details, see Pointers in Using Swift with Cocoa and Objective-C.

CMutablePointer<NSRange> dead end

I'm trying to call lineFragmentRectForGlyphAtIndex method of NSLayoutManager object in Swift. Its description is that:
func lineFragmentRectForGlyphAtIndex(glyphIndex: Int, effectiveRange: CMutablePointer<NSRange>)
But I can't figure it out how am I suppose to call it. According to Apple docs I have to call it like this:
let someRange : NSRange = ...
layoutManager.lineFragmentRectForGlyphAtIndex(0, effectiveRange: &someRange)
That's what documentation says. But I get an error: 'NSRange' is not a subtype of '#lvalue $T5'
What should I do?
Try making it a var instead of a let:
var someRange: NSRange = ...
layoutManager.lineFragmentRectForGlyphAtIndex(0, effectiveRange: &someRange)
Basically: using the & on a var gives you something compatible with a CMutablePointer, but a let is not supposed to be mutable. Hence the type error.
If you want to pass a null pointer, just write nil instead of &someRange (and then of course you don't need to declare the extra var).