SWIFT XCODE error - xcode

I am a complete beginner in coding. I managed to get some working code in Playground but once I moved to building a project nothing worked.
This is for OS X.
I have used the following simple lines of code in Playground and AppDelegate contexts. It runs and outputs to the console without error in Playground but returns an error in AppDelegate.swift - Expected declaration for the " for num in availcrop" line with a red arrow under the f in for.
var availcrop = [0, 1, 2, 3, 4, 5, 6, 7]
for num in availcrop
{
var ran = 1000+randInt(2000)
availcrop[num] = ran
println(availcrop[num])
}
- the println is not planned for the project. Just in the Playground for testing
Both have imported Cocoa. One runs and the other crashes. In Playground the array name avail crop is blue implying it is recognised I suppose. In the AppDelegate.swift it remains grey.

Once you're dealing with classes and objects, code generally needs to be inside some method so that it can be invoked by name.
Try:
func printRandoms {
// Your code here
}

Related

Can't get CoreSpotlight to work properly on the Mac... sample code anyone?

Can someone point me to some sample code for using CoreSpotlight on the Mac? I can’t find a single sample code example (for mac, plenty of iOS ones out there). I have already successfully implemented CS on our iOS app.
Using code similar to what I used for iOS, I’m getting it to index the content, but it’s very minimal: it gives me the generic app icon for the content (rather than the custom thumbnail image I specify) and has no description, etc (on the Spotlight pane, the entire right side is blank).
Also, it's unclear to me what code I need to add to AppDelegate to handle the click on the spotlight data. I used `func application(_ application: NSApplication, continue userActivity: NSUserActivity, restorationHandler:) on iOS but this doesn't seem to get called on the Mac.
Here's the code I'm using to index the content:
attributeSet.title = content.name
attributeSet.contentDescription = content.description
if let image = image {
let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)!
let bitmapRep = NSBitmapImageRep(cgImage: cgImage)
attributeSet.thumbnailData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!
}
let item = CSSearchableItem(uniqueIdentifier:content.uuid, domainIdentifier: "com.my.app.bundle.id", attributeSet: attributeSet)
searchableIndex?.indexSearchableItems([item]) { error in
if let error = error {
NSLog("CoreSpotlight Indexing error: \(error.localizedDescription)")
}
}
And this is an example of what I get in Spotlight:
A bit of sample code would clear this right up, Methinks.
Thanks in advance.

How to move an image in Lua?

I am new to Lua programming and I am having problems while trying to move an image from a set of coordinates to another.
What I am trying to create is to be used with the X-Plane flight simulator. There is a library called SASL (www.1-sim.com), that was created to make plugins (for X-Plane) creation easir, since the default language is C++ and many people find it difficult.
In general, SASL works as a bridge between Lua and X-Plane, in general lines, the scripts you write reads some data straight from X-Plane (DataRefs) while it is running and depending on the code you wrote its execute commands or many other things that it is possible.
So, when using SASL to create cockpit/panel gauges it uses a base file, named 'avionics.lua' that works as a class and loads all gauges you create for the specific aircraft you are working on. For example my avionics.lua file looks like this:
size = { 2048, 2048 }
components = {
flaps {};
};
where, 'size' is the size that will be used for things to be drawn and components is an array of gauges, in this case the flaps gauge.
The rest of the work is to create the gauge functionality and this is done in a separate file, in my case, called 'flaps.lua'.
Within flaps.lua, is where I need to code the flaps indicator functionality which is to load 2 images: one for the back ground and the second one for the flaps indicator.
The first image is a fixed image. The second one will move throught the 'y' axis based on the flaps indicator DataRef (flapsDegree property below).
The code below when X-Plane is running displays the background image and the flaps indicator on its first stage which is 0 as you can see on the image.
size = {78,100}
local flapsDegree = globalPropertyf("sim/cockpit2/controls/flap_ratio")
local background = loadImage("gfx/Flaps.png")
local indicator = loadImage("gfx/Flaps_Indicator.png")
local flaps = get(flapsPosition)
components = {
texture { position = {945, 1011, 60, 100}, image = background},
texture { position = {959, 1097, 30, 9}, image = indicator},
}
Image
Now, the problem comes when I need to implement the logic for moving the 'indicator' image through the 'y' axis.
I have tried this code without success:
if flaps == 0.333 then
indicator.position = {959, 1075, 30, 9}
end
So how could I accomplish that?
I am not familiar with the SALS library. I just had a quick look into it.
Everything you need to know is in the manuals on the website you linked.
In particular http://www.1-sim.com/files/SASL300.pdf
Everytime your screen is updated each components draw() function will be called.
So if you want to change something dynamically you have to put that into the component's draw function.
If you open the SALS sources you'll find basic components which show you how to use that stuff. One of them is needle.lua:
-- default angle
defineProperty("angle", 0)
-- no image
defineProperty("image")
function draw(self)
local w, h = getTextureSize(get(image))
local max = w
if h > max then
max = h
end
local rw = (w / max) * 100
local rh = (h / max) * 100
drawRotatedTexture(get(image), get(angle),
(100 - rw) / 2, (100 - rh) / 2, rw, rh)
end
If you check the manual you'll find that there is not only a drawRotatedTexture function but many other functions for drawing stuff. Just play around. Try drawTexture for your purpose.
If you don't know what you have to program, open every single lua file in the library and read it together with the Lua reference manual and the SALS documentation until you understand what is going on. Once you understand the existing code you can extend it with ease.

permanently modifying RGB gamma table

The following script sets a custom gamma table for the current display. It works for about a second before the screen resets to its default profile.
#!/usr/bin/swift
import CoreGraphics
var redTable: [CGGammaValue] = [0, 0]
var greenTable: [CGGammaValue] = [1, 0]
var blueTable: [CGGammaValue] = [0, 1]
CGSetDisplayTransferByTable(CGMainDisplayID(), 2, &redTable, &greenTable, &blueTable)
sleep(5)
What causes this reset without me calling CGDisplayRestoreColorSyncSettings() directly?
How would I go about permanently adjusting the gamma table?
OK, found it. I was running flux which reconfigured the display profile every second or so. Quitting the app fixed it.

Swift constant defined with LET sometimes produces EXC_BAD_ACCESS (EXC_I386_GPFLT) on read (OSX)

In my AppDelegate I have a constant for a statusbar icon, used when the application is busy:
class AppDelegate: NSObject, NSApplicationDelegate {
let busyImage = NSImage(named: "BusyStatus");
...
In another class I'm accessing this several times over the time the app is running. On a Macbook Air with SSD I sometimes get an
EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: EXC_I386_GPFLT
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 libswiftCore.dylib 0x0000000103876cf9 swift_unknownRetain + 41
1 de.test.myapp 0x000000010304743b TestApp.AppDelegate.busyImage.getter : ObjectiveC.NSImage? (in TestApp) (AppDelegate.swift:0)
2 de.test.myapp 0x0000000102f9aa77 TestApp.Sync.(update (TestApp.Sync) -> () -> ()).(closure #2) (in TestApp) (Sync.swift:271)
The code there:
statusBarItem!.image = appDelegate!.busyImage
It's in a block called in the Main Thread:
let updateBlock: () -> () = {
appDelegate!.statusBarItem!.image = self.appDelegate!.busyImage
[... other code ...]
}
if NSThread.isMainThread()
{
updateBlock()
}
else
{
dispatch_sync(dispatch_get_main_queue(),updateBlock)
}
What can cause this and how to avoid this?
Problem seems to be gone since swift 2.
Never had this issue again and changed absolutely nothing in my code.
Hello People from the Internet,
My env is macOS 10.15.4 and I am running XCode 11.5 (11E608c) with Swift 5.
I have exactly the same issue with a little piece of code here which fails 100% of the time when using the rotation:
override func rotate(delta: float2) {
let sensitivity: Float = 0.005
rotation.y += delta.x * sensitivity // FAILS with Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
_viewMatrix = updateViewMatrix()
}
This code does not look weird at all. rotation is a vector of floats defined in the Class as:
var rotation: float3 = [0, 0, 0]
Now, I spent some time trying many versions of the same function and if I rewrite it as:
override func rotate(delta: float2) {
let sensitivity: Float = 0.005
var deltaX: Float = delta.x * sensitivity
rotation.y += deltaX
_viewMatrix = updateViewMatrix()
}
it now runs smoothly. This is crazy since I see no obvious reason. I do not try to change a constant and even the linter advises me to change the var to let in deltaX definition.
I feel like this is a Swift issue but this is worrying for a 5th version of a language used by many.
I would update my answer if I find a solution or at least a valid explanation.
Live long and prosper lads!

Searching Serial Ports with IOKit - Swift

I'm trying to understand IOKit and how it allows me to access serial ports in a Swift program.
The class I'm manipulating at the moment is as follows:
import Foundation
import Cocoa
import IOKit.serial.IOSerialKeys
class Serial {
init() {
}
#IBOutlet var serialListPullDown : NSPopUpButton!
func refreshSerialList(defaultprompt: String) {
// remove everything from the pull down list
serialListPullDown?.removeAllItems()
// ask for all the serial ports
IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(kIOSerialBSDServiceValue), io_iterator_t)
}
}
Based on what I've read I think I've setup IOServiceMatchingServices correctly but I'm getting several errors such as "Expected member name or constructor call after type name" and "'o_iterator_t.Type' is not convertible to 'UnsafeMutualPointer'"
What does this mean?
A few different issues going on in there -- let's get your imports squared away first. It looks like you need these two:
import IOKit
import IOKit.serial
For the parameters, it'll be easier to see what we're working with if we define them as local variables, like so:
// this one's easy, just grabbing a constant from IOKit.serial
let masterPort: mach_port_t = kIOMasterPortDefault
// here we get back an Unmanaged<CFMutableDictionary> and need to convert it to
// a CFDictionary using takeRetainedValue()
let classesToMatch: CFDictionary = IOServiceMatching(kIOSerialBSDServiceValue).takeRetainedValue()
// the iterator that will contain the results of IOServiceGetMatchingServices
var matchingServices: io_iterator_t = 0
And lastly, you call the method:
// note that the last parameter is an UnsafeMutablePointer<io_iterator_t>
// so we need to prefix matchingServices with an ampersand (&)
let kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, &matchingServices)
if kernResult == KERN_SUCCESS {
// success
} else {
// error
}
This feels pretty near the edge of what Swift can handle right now -- definitely read these two pages well before going further:
Interacting with C APIs (Pointers section)
Working with Cocoa Data Types (Unmanaged Objects section)
Lastly, make sure you can get into the converted Swift declarations for the IOKit framework. There are a lot of useful comments and you'll be able to see which parameters and return values are unmanaged or pointers (since I don't think this framework's official documentation has been updated yet).

Resources