Swift 3 unresolved identifier CGColorGetComponents [duplicate] - uicolor

This question already has answers here:
Xcode 8 Beta 4 CGColor.components unavailable
(5 answers)
Closed 6 years ago.
How can I refactor this code in Swift 3?:
extension UIColor {
var hexString: String {
// Produces "Use of unresolved identifier 'CGColorGetComponents'"
let components = CGColorGetComponents(self.cgColor)
....
}
}

var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0, a:CGFloat = 0
self.getRed(&r, green: &g, blue: &b:, alpha: &a)
...

Related

c++11. How to get element from tuple without const [duplicate]

This question already has answers here:
C++0x: How can I access variadic tuple members by index at runtime?
(4 answers)
Closed 6 years ago.
I'm trying to do this.
int flag = 0;
if(big.size() <= small.size())
flag = 1; //use float
tuple<long, float> tup (1234.5678, 12341234.1234);
auto foo = get<flag>(tup);
But I get errors:
error: the value of 'flag' is not usable in a constant expression
cout << get<flag>(tup);
-and-
note: 'int flag' is not const
int flag = 0;
Since the value of flag is not known at compile time, it cannot be used a template parameter.
You'll need to use something like:
tuple<long, float> tup (1234.5678, 12341234.1234);
if ( flag )
{
auto foo = get<1>(tup);
}
else
{
auto foo = get<0>(tup);
}

Minor Syntax issue regarding Swift 3.0 and a for loop

I recently just converted my code to the Swift 3.0 syntax that came with the Xcode 8 beta. I ran into several lines of code that I needed to change in order for the code to work with the latest syntax. I was able to correct all lines of code except for an error that I get regarding a for loop that I use to allow my background image to loop continuously.
The exact error message that I get is: Ambiguous reference to member '..<'
for i:CGFloat in 0 ..< 3 {
let background = SKSpriteNode(texture: backgroundTexture)
background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * i), y: self.frame.midY)
background.size.height = self.frame.height
background.run(movingAndReplacingBackground)
self.addChild(background)
}
Don't use a floating point type as loop index
for i in 0 ..< 3 {
let background = SKSpriteNode(texture: backgroundTexture)
background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * CGFloat(i)), y: self.frame.midY)
background.size.height = self.frame.height
background.run(movingAndReplacingBackground)
self.addChild(background)
}
Try with this:
for i in 0..<3{
let index = CGFloat(i)
//Your Code
let background = SKSpriteNode(texture: backgroundTexture)
background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * index), y: self.frame.midY)
background.size.height = self.frame.height
background.run(movingAndReplacingBackground)
self.addChild(background)
}
The problem is you are performing for-loop on Int and you are also specifying it as a CGFloat. So, there a confusing between both the types.

AudioToolbox/AudioUnits (AudioFileWriteBytes) unavailable in Swift?

Apple's documentation :
AudioToolbox Framework Reference > Audio File Services Reference > Reading and Writing Audio Files > AudioFileWriteBytes
Declaration Swift func AudioFileWriteBytes(_ inAudioFile: AudioFileID,
_ inUseCache: Boolean,
_ inStartingByte: Int64,
_ ioNumBytes: UnsafeMutablePointer<UInt32>,
_ inBuffer: UnsafePointer<Void>) -> OSStatus
Code in XCode Version 7.0 beta 4 (7A165t)
audioErr = AudioFileWriteBytes(audioFile, false, Int64(sampleCount * 2), bytesToWriteMem, sampleMem as! UnsafePointer<Void>)
XCode's reponse :
Cannot invoke 'AudioFileWriteBytes' with an argument list of type '(AudioFileID, Bool, Int64, UnsafeMutablePointer<UInt32>, UnsafePointer<Void>)'
Any idea ?
EDIT :
Thanks Martin R for your response, here is my full code and i don't understand why the AudioFileWriteBytes call returns an error ... :
import Foundation
import AudioToolbox
import Darwin
import AudioUnit
import CoreFoundation
extension Int {
func format (f:String) -> String {
return NSString(format:"%\(f)d", self) as String
}
}
let SAMPLE_RATE:Float64 = 44100 // 1
let DURATION = 0.1 // 2
// #define FILENAME_FORMAT #"%0.3f-square.aif" 3 skipped
if (Process.arguments.count < 2) {
print("Usage: CAToneFileGenerator n\n(where n is tone in Hz)")
exit(0)
}
var hz:Double = atof(Process.arguments[1]) // 4 (atof convert ASCII string to double)
assert(hz > 0)
print("generating \(hz) tone")
var fileName:String = String(format:"%d-square.aif", hz) // 5
var filePath:String = NSFileManager.defaultManager().currentDirectoryPath.stringByAppendingPathComponent(fileName)
var fileURL:NSURL = NSURL.fileURLWithPath(filePath) // the Audio File Services functions take URLs, not file paths
// Prepare the format
var asbd = AudioStreamBasicDescription() // 6
memset(&asbd, 0, sizeof(AudioStreamBasicDescription)) // 7
asbd.mSampleRate = SAMPLE_RATE // 8
asbd.mFormatID = AudioFormatID(kAudioFormatLinearPCM)
asbd.mFormatFlags = AudioFormatFlags(kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked)
asbd.mBitsPerChannel = 16
asbd.mChannelsPerFrame = 1
asbd.mFramesPerPacket = 1
asbd.mBytesPerFrame = 2
asbd.mBytesPerPacket = 2
// Set up the file
var audioFile:AudioFileID = AudioFileID()
var audioErr:OSStatus = noErr
audioErr = AudioFileCreateWithURL(fileURL, // 9
AudioFileTypeID(kAudioFileAIFFType),
&asbd,
.EraseFile,
&audioFile)
// 1 -> AudioFileFlags(kAudioFileFlags_EraseFile)
assert(audioErr == noErr)
// Start writing samples
var maxSampleCount:CLong = CLong(SAMPLE_RATE * DURATION) // 10
var sampleCount:CLong = 0
var bytesToWrite:UInt32 = 2
/*
var bytesToWriteMem = UnsafeMutablePointer<UInt32>.alloc(1)
bytesToWriteMem.initialize(bytesToWrite)
*/
var wavelengthInSamples:Double = SAMPLE_RATE / hz // 11
var sample:UInt16
//var sampleMem = UnsafeMutablePointer<UInt16>.alloc(1)
//sampleMem.initialize(sample)
while sampleCount < maxSampleCount {
for i in 0..<Int(wavelengthInSamples) {
// Square wave
if ( i < Int(wavelengthInSamples/2)) { // 12
sample = UInt16.max // 13
} else {
sample = UInt16.min
}
//let bytesToWrite2 = bytesToWrite
audioErr = AudioFileWriteBytes(audioFile, // 14
false,
Int64(sampleCount * 2),
&bytesToWrite, //UnsafeMutablePointer<UInt32>
&sample) //UnsafePointer<Void>
assert(audioErr == noErr)
sampleCount++ // 15
}
}
/*
bytesToWriteMem.destroy()
bytesToWriteMem.dealloc(1)
sampleMem.destroy()
sampleMem.dealloc(1)
*/
audioErr = AudioFileClose(audioFile) // 16
assert(audioErr == noErr)
print("wrote \(sampleCount) samples")
That was tricky to find, because the error message does not help at all.
The problem is that the type of the second parameter of AudioFileWriteBytes() is Boolean, not Bool:
audioErr = AudioFileWriteBytes(audioFile,
Boolean(0), // <--- HERE
Int64(sampleCount * 2),
&bytesToWrite,
&sample)
For more information about the difference between Boolean and Bool
see for example Type 'Boolean' does not conform to protocol 'BooleanType'.
Update: As of Swift 2/Xcode 7, the Mac type Boolean is mapped
to the Swift Bool, so you have to pass false or true now:
audioErr = AudioFileWriteBytes(audioFile,
false, // <--- HERE
Int64(sampleCount * 2),
&bytesToWrite,
&sample)

How to resize NSImage in swift? [duplicate]

This question already has answers here:
How to resize NSImage?
(12 answers)
Closed 6 years ago.
I want to resize an NSImage from 512px to 60px, I found only the code for iOS, but nothing for OSX.
I found a function on GitHub, it is working fine for me.
func resize(image: NSImage, w: Int, h: Int) -> NSImage {
var destSize = NSMakeSize(CGFloat(w), CGFloat(h))
var newImage = NSImage(size: destSize)
newImage.lockFocus()
image.drawInRect(NSMakeRect(0, 0, destSize.width, destSize.height), fromRect: NSMakeRect(0, 0, image.size.width, image.size.height), operation: NSCompositingOperation.CompositeSourceOver, fraction: CGFloat(1))
newImage.unlockFocus()
newImage.size = destSize
return NSImage(data: newImage.TIFFRepresentation!)!
}

Is there a way to create enums in typescript that are ambient?

edit after release of typescript 0.9: enums are now supported:
enum Select { every, first, last }
original question:
Enums in typescript were discussed here but no solution leads to an ambient design. An ambient enum definition would mean that the enum is handled by the compiler only and the compiled js output files only deal with the raw numerical values. Like in C++11.
The closest I get is
declare var Color = { red: 1, blue: 2, green: 3 } // DOES NOT COMPILE
but the compiler does not accept this: "Ambient variable cannot have initializer".
edit
incorporating dmck's answer:
declare var Color: { Red: number; Green: number; Blue: number; };
This does not output any js code. In other words, it is ambient. This however makes it useless as well:
declare var Color: { Red: number; Green: number; Blue: number; };
function test() {
var x = Color.Blue; // null ref exception, no Color object
console.log(x == Color.Red);
}
will produce a runtime error, as Color is not defined in js. The ts declaration just claims that there is some Color object in js, while in fact, without definition, there is none. Ti fix this we can add
var Color = {
Red: 1,
Green: 2,
Blue: 3
};
but now the enum implementation is not "ambient" in the sense that the typescript compiler does what a C++ compiler does, reducing the enum values at all occurencies to plain numbers. The current ambient declarations allow type checking but not such replacement.
TypeScript 0.9 allows this:
declare module A { export enum E { X, Y, Z } }
Adding an answer as there are new features for this starting with TypeScript 1.4;
using const enum give the expected result.
This is with a normal enum:
//TypeScript:
enum StandardEnum {FirstItem, SecondItem, ThirdItem};
//Compiled javascript:
var StandardEnum;
(function (StandardEnum) {
StandardEnum[StandardEnum["FirstItem"] = 0] = "FirstItem";
StandardEnum[StandardEnum["SecondItem"] = 1] = "SecondItem";
StandardEnum[StandardEnum["ThirdItem"] = 2] = "ThirdItem";
})(StandardEnum || (StandardEnum = {}));
This is with a const enum:
//TypeScript:
const enum ConstantEnum { FirstItem, SecondItem, ThirdItem };
//Compiled javascript:
;
This blog post explains it with more details : https://tusksoft.com/blog/posts/11/const-enums-in-typescript-1-4-and-how-they-differ-from-standard-enums
You could do something like this:
declare var Color: { Red: number; Green: number; Blue: number; };
Remember that by design ambient declarations have no effect on the output of your code. So somewhere you'll need to actually declare Color and the values of each enum member.

Resources