This question already has answers here:
Crash when casting the result of arc4random() to Int
(7 answers)
Closed 8 years ago.
I am trying to fetch a random item from an array containing 3 strings as follows :
func selectRandomImage () {
var imageName : String? //Optional
var arrayCount : NSNumber = animalsArray.count //Bridges to an NSNumber
var x : Int = Int(arc4random())%(arrayCount.integerValue)
var name : String = animalsArray[x] as String
println("Name is \(name)")
}
However every 5 runs or so of the code, I am getting a crash with EXC_BAD_INSTRUCTION.
Could anyone advise on what could be wrong or how to troubleshoot ?
Thanks !
arc4random doesent work well with swift, it crushes when you try to cast it to Int
Try Int(rand()) instead of arc4random()
Related
This question already has an answer here:
Cannot pass immutable value as inout argument: function call returns immutable value
(1 answer)
Closed 6 years ago.
I'm a complete Swift newbie, but I'm writing an app for BLE using swift and have run into an issue. I'm working off of some open source code that I found in order to understand how to structure an iOS app and communicate with BLE, and when I converted it to Swift 3, a number of errors came up.
Code:
func int8Value() -> Int8 {
var value: Int8 = 0
copyBytes(to: &UInt8(value), count: MemoryLayout<Int8>.size)
return value
}
Error:
Cannot pass immutable value as inout argument: function call returns immutable value
I've been looking online for solutions to this and have found the following:
NSData to [Uint8] in Swift
CBCharacteristic value in swift3
I tried to implement these, taking a look at the following lines of code:
if let data = characteristic.value {
var bytes = Array(repeating: 0 as UInt8,count:someData.count/MemoryLayout<UInt8>.size)
data.copyBytes(to: &bytes, count:data.count)
}
and
let data = "foo".data(using: .utf8)!
let array = [UInt8](data)
let array = data.withUnsafeBytes {
[UInt8](UnsafeBufferPointer(start: $0, count: data.count))
}
I don't really understand the correlation between the them other than a few common variables. Can someone explain what is happening inside of the CopyBytes function (what "to" and "count" are doing), what the error is coming from, and if the examples I've been looking at have anything to do with the method I'm trying to fix?
It looks like there was an issue with the type casting from Int8 to UInt8, and taking the address of the resulting UInt8 conversion. The result of the cast is an immutable value, whose memory location cannot be passed as the function argument. If you simply initialize the variable as an unsigned int, it should pass the address just fine.
The following code should work:
func int8Value() -> Int8 {
var value: UInt8 = 0
copyBytes(to: &value, count: MemoryLayout<Int8>.size)
return Int8(value)
}
This question already has answers here:
Swift - Resolving a math operation in a string
(4 answers)
Closed 7 years ago.
I'm trying to convert a string like so:
var equation = "8+3*4/5-1*(5+5)"
to an Int so that it will calculate it with order of operations but with my code it is just return nil. Here is what I have tried
var answer = Int(equation)
Try it this way:
var equation = "\(8+3*4/5-1*(5+5))" //"0"
And this way you can convert it to Int
var answer = equation.toInt() // 0
Or you can directly do it this way:
var equation = 8+3*4/5-1*(5+5) // 0
And As Martin R suggested if you want to do math operation in a string you can do it this way:
let expn = NSExpression(format:"8+3*4/5-1*(5+5)")
println(expn.expressionValueWithObject(nil, context: nil)) //"0"
Which will result as String but you can convert it to Int as I suggested above.
Here is original link for math operation in a string: Swift - Resolving a math operation in a string
This question already has answers here:
How to find index of list item in Swift?
(23 answers)
Closed 7 years ago.
Is there a "better"(less verbose) way of doing this?
var found: Int?
for i in 0...myArray-1 {
if myArray[i] == 3 {
found = i
}
}
similar to
let i = find(myArray, "1")
but for Int ?
This question is slightly "different" than How to find index of list item in Apple's swift? because it directly address the find function for Int, instead of String. Granted, the only difference is the title and pointing out that you can remove the quotation marks to get Int.
Here's an Int example
let myArray = [1, 2, 3]
var i = find(myArray, 2)
Good luck
This question already has answers here:
Converting String to Int with Swift
(31 answers)
Closed 8 years ago.
I'm working in a small project and I faced this problem : text field is String by default so I need to take the input and convert it to integer then calculate I was searching for a way to solve the converting problem and I didn't find any working solution so can any one help me please ?
try like this
In Swift 2.0, toInt(),replaced with initializers. (In this case, Int(someString).)
let myString : String = "50"
let x : Int? = Int(myString)
if (x != null) {
// converted String to Int
}
myString.toInt() - convert the string value into int .
This question already has answers here:
Passing lists from one function to another in Swift
(2 answers)
Passing an array to a function with variable number of args in Swift
(7 answers)
Closed 8 years ago.
In "The Swift Programming Language", Functions and Closures, there is a sample code to calculate the total as below:
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
As part of the following experiment, I tried the following function to calculate the average
func averageOf(numbers : Int...) -> Int {
var argument:Array = numbers
var average = sumOf(argument) / numbers.count
return average
}
However, I get the following error
[Int] is not convertible to Int
I have also tried the following line with no success
var average = sumOf(numbers) / numbers.count
Any idea whats going on underneath? Why is sumOf parameter is treating it as Int instead of an array when the book clearly states that
“Functions can also take a variable number of arguments, collecting
them into an array.”
It seems to me you function is ok if you try to call it properly.
sumOf(25,23,43,23)
But if you would like to call array use this code :
import UIKit
var someInts = [Int]()
someInts.append(8)
someInts.append(6)
someInts.append(6)
someInts.append(3)
someInts.append(5)
func sumOf(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf(someInts)
The main problem that in function you declare parameter not as array but like undefined amount of the integers
Just change definition of method To
func sumOf(numbers: [Int]) -> Int
Instead Of
func sumOf(numbers: Int...) -> Int
Because you are passing array as an argument to func sumOf function, which is not expected as its define.