I am very new to Swift 2.0 and am pretty stuck here...
I have created a random number generator based off a user set range for low and high limits. This function worked great with my test function when I could set the variables for low and high to Uint32
Once I tried to store the low/high range in NSUserDefaults as an integer. Now when I try to load the values set by the user for the low and high to use in my function below it gives me the error that it needs to be a UInt32 value.
The problem is.... I cannot seem to figure out how to save them in NSUser as that type. Or unwrap it as that type coming out of the UserDefaults.
My specific error message is...
ERROR IS Binary Operator + cannot be applied to operands of type UInt32 and In
Thanks so much ahead of time for your help and time I truly appreciate it! You guys are awesome here!
Let me know if there is anything else you need from me :)
//CREATE SAVE SETTINGS FOR LOW AND HIGH RANGE
NSUserDefaults.standardUserDefaults().integerForKey("CatLowRange")
NSUserDefaults.standardUserDefaults().integerForKey("CatHighRange")
//Variables to load in values from NSUserDefaults on load
var catLowRange = 0 //Load In Low Range From NSUser
var catHighRange = 40 //Load In High Range From NSUser
//LOAD IN VALUES TO VARIABLES FROM NSUSERDEFAULTS
catLowRange = NSUserDefaults.standardUserDefaults().integerForKey("CatLowRange")
catHighRange = NSUserDefaults.standardUserDefaults().integerForKey("CatHighRange")
**//My Function To Generate RandNumber...**
*ERROR IS Binary Operator + cannot be applied to operands of type UInt32 and Int*
randomNumber = arc4random_uniform (catHighRange - catLowRange) + catLowRange
For anyone wondering... Thanks to Adam we have an answer... Here is the code broken down how I used his suggestion to make this thing work :)
//WORKING METHOD!?
//vars for use
let catLowRange : UInt32 = 0
let catHighRange : UInt32 = 40
var randNumGenerated : UInt32 = 0
//SAVEPOINTS (STEP 1 - save the UInt32s as int for saving)
NSUserDefaults.standardUserDefaults().setInteger(Int(catLowRange), forKey: "CatLowRange")
NSUserDefaults.standardUserDefaults().setInteger(Int(catHighRange), forKey: "CatHighRange")
//LOAD (STEP 2 - Take Int save as a UInt32 now)
let catLowRangeLoad = UInt32(NSUserDefaults.standardUserDefaults().integerForKey("CatLowRange"))
let catHighRangeLoad = UInt32(NSUserDefaults.standardUserDefaults().integerForKey("CatHighRange"))
//FUNCTION TEST
randNumGenerated = arc4random_uniform (catHighRangeLoad - catLowRangeLoad) + catLowRangeLoad
//CHECK
print ("catLowRange = \(catLowRange)")
print ("catLowRangeLoad = \(catLowRangeLoad)")
print ("catHighRange = \(catHighRange)")
print ("catHighRangeLoad = \(catHighRangeLoad)")
print ("randNumGen = \(randNumGenerated)")
Use this code (updated for swift 3):
let number : UInt32 = 8
UserDefaults.standard.set(NSNumber(value: number), forKey: "key")
let number2 = (UserDefaults.standard.value(forKey: "key") as? NSNumber)?.uint32Value
Related
i have 3 Doubles, their values are random, and i am trying to achieve a comparison between them
so my code is
let double1 = 10.00 // notes: they're all random between 1-100 so i don't know what this will be
let double2 = 7.66
let double3 = 6.43
but, i tried
if (double1?.isLess(than: 50.0))! {
print("Low")
} else {
print("High")
}
but as i mentioned, this can't be done due to the random values, i need to compare two of them to each other, to make sure that one of them will be higher
Its actually rather very simple:
let maxDouble = max(max(double1, double2), double3) // prints 10
I am trying to do some computation on the raw PCM samples of a mp3 files I'm playing with an AVAudioEngine graph. I have a closure every 44100 samples that provides an AVAudioPCMBuffer. It has a property channelData of type UnsafePointer<UnsafeMutablePointer<Float>>?. I have not worked with pointers in Swift 3 and so I'm unclear how to access these Float values.
I have the following code but there are many issues:
audioPlayerNode.installTap(onBus: 0,
bufferSize: 1024,
format: audioPlayerNode.outputFormat(forBus: 0)) { (pcmBuffer, time) in
let numChans = Int(pcmBuffer.format.channelCount)
let frameLength = pcmBuffer.frameLength
if let chans = pcmBuffer.floatChannelData?.pointee {
for a in 0..<numChans {
let samples = chans[a]// samples is type Float. should be pointer to Floats.
for b in 0..<flength {
print("sample: \(b)") // should be samples[b] but that gives error as "samples" is Float
}
}
}
For instance, how do I iterate through the UnsafeMutablePointer<Floats which are N float pointers where N is the number of channels in the buffer. I could not find discussion on accessing buffer samples in the Apple Docs on this Class.
I think the main problem is let samples = chans[a]. Xcode says chans is of type UnsafeMutablePointer<Float>. But that should be NumChannels worth of those pointers. Which is why I use a in 0..<numChans to subscript it. Yet I get just Float when I do.
EDIT:
hm, seems using chans.advanced(by: a) instead of subscripting fixed things
Here is what I've found:
let arraySize = Int(buffer.frameLength)
let samples = Array(UnsafeBufferPointer(start: buffer.floatChannelData![0], count:arraySize))
This is assuming buffer is the name of your AVAudioPCMBuffer.
This way you can avoid pointers, which is likely much simpler. Now you can actually search through the data using a for loop.
I'm trying to initialize Data from an UnsafeBufferPointer, but it's throwing an EXC_BAD_ACCESS when it hits the third line. Help appreciated.
let pointer = UnsafePointer<UInt8>(UnsafePointer<UInt8>(bitPattern: 15)!)
let buffer = UnsafeBufferPointer<UInt8>(start: pointer, count: 1)
let data = Data(bytes: Array(buffer)) // EXC_BAD_ACCESS
My end goal is to convert bits of data to some human readable format (eg., convert a bit pattern of 15 to "F"). I was hoping to initialize a String from the data object as a hex value. I'm open to better and correct ways of going about this.
I am new to swift so need some help. want to get a number from text field (which input by user) and sum it then store it for the next time. So when user come back in other time and input another number will be summed to the previous number.
let say, user input 10 and close the app then come back and input 5. the app will sum them and give 15 so on and so forth.
thanks for help
You can use NSUserDefault to save the value.
Example : https://www.hackingwithswift.com/read/12/2/reading-and-writing-basics-nsuserdefaults
Write :
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(10, forKey: "value")
Read :
let defaults = NSUserDefaults.standardUserDefaults()
let value = defaults.integerForKey("value")
You can also use code data : https://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started
many thanks for you all
I just found the best way. I just used this code
first read it:
let defaults = NSUserDefaults.standardUserDefaults()
let X = defaults.integerForKey("Cost")
convert the field.text! in to integer and add the previous value "X"
Cost = integer! + X
re-write the default
defaults.setValue(Cost, forKey: "Cost")
defaults.synchronize()
done
Current learning Swift, there are ways to find max and min value for different kind of Integer like Int.max and Int.min.
Is there a way to find max value for Double and Float? Moreover, which document should I refer for this kind of question? I am currently reading Apple's The Swift Programming Language.
As of Swift 3+, you should use:
CGFloat.greatestFiniteMagnitude
Double.greatestFiniteMagnitude
Float.greatestFiniteMagnitude
While there’s no Double.max, it is defined in the C float.h header, which you can access in Swift via import Darwin.
import Darwin
let fmax = FLT_MAX
let dmax = DBL_MAX
These are roughly 3.4 * 10^38 and 1.79 * 10^308 respectively.
But bear in mind it’s not so simple with floating point numbers (it’s never simple with floating point numbers). When holding numbers this large, you lose precision in a similar way to losing precision with very small numbers, so:
let d = DBL_MAX
let e = d - 1.0
let diff = d - e
diff == 0.0 // true
let maxPlusOne = DBL_MAX + 1
maxPlusOne == d // true
let inf = DBL_MAX * 2
// perhaps infinity is the “maximum”
inf == Double.infinity // true
So before you get into some calculations that might possibly brush up against these limits, you should probably read up on floating point. Here and here are probably a good start.
AV's answer is fine, but I find those macros hard to remember and a bit non-obvious, so eventually I made Double.MIN and friends work:
extension Double {
static var MIN = -DBL_MAX
static var MAX_NEG = -DBL_MIN
static var MIN_POS = DBL_MIN
static var MAX = DBL_MAX
}
Don't use lowercase min and max -- those symbols are used in Swift 3.
Just write
let mxFloat = MAXFLOAT
You will get the maximum value of a float in Swift.
Also CGFloat.infinity, Double.infinity or just .infinity can be useful in such situations.
Works with swift 5
public extension Double {
/// Max double value.
static var max: Double {
return Double(greatestFiniteMagnitude)
}
/// Min double value.
static var min: Double {
return Double(-greatestFiniteMagnitude)
}
}