Modifying an array passed as an argument to a function in Swift
You need to change the definition of modify
to accept an inout
parameter. By default, function arguments are immutable, but by using the inout
keyword, you can make them mutable. You also need to pass the argument by reference.
func modify( arr: inout [String]) {
arr.removeFirst()
}
var stringArr = ["a","b"]
modify(arr: &stringArr) //stringArr = ["b"] after the function call
Swift - Changing an array value of function call
This is because f
parameter is an immutable array
. You can change this to a mutable array
parameter by using the function signature as follows
func calculateBoundary (var f:[Float], var s:[Float], n:NSInteger) -> (forceBound1:Float, forceBound2: Float, displacement:[Float]) { // }
If you want to also modify the original arrays passed to the function, you need to use inout
parameters.
func calculateBoundary (inout f:[Float],inout s:[Float], n:NSInteger) -> (forceBound1:Float, forceBound2: Float, displacement:[Float]) { // }
You can call it like this
var f : [Float] = [1.0,2.0]
var g : [Float] = [1.0,2.0]
let result = calculateBoundary(&f, &g, 1)
How do you modify array parameter in swift
func tt(a:[UInt8]) {
a[2]=10
}
In above function, the function parameter a
is a let
constant, you can't change it inside the function.
You need to use inout
parameter to be able to modify this.
var a: [UInt8] = [1,2,3,4,5]
func tt(a: inout [UInt8]) {
a[2] = 10
}
tt(a: &a)
modify an array within a function does not work
The arrays inside alter_them
are a copy of the originals.
Use inout
to modify the original arrays:
func alter_them(inout data: [String], inout data2: [String]){
for (i, _) in data.enumerate(){
data[i] = "1"
}
for (i, _) in data2.enumerate(){
data2[i] = "2"
}
}
alter_them(&Draw_S, data2: &Draw_E)
Passing an array to a function with variable number of args in Swift
Splatting is not in the language yet, as confirmed by the devs. Workaround for now is to use an overload or wait if you cannot add overloads.
How to pass an Array to function as a parameter in Swift?
You can simply use [DataModel]
as type for function parameter
Something like
func parsedData(parsedResuls: [DataModel]) {
}
Swift: Pass array by reference?
Structs in Swift are passed by value, but you can use the inout
modifier to modify your array (see answers below). Classes are passed by reference. Array
and Dictionary
in Swift are implemented as structs.
Trying to pass an array to function in swift
Every language has a natural way code wants to be written. As part of the process for learning a language, try to learn how code should be written in that language.
In this example, you want to combine the elements of two arrays into an array of dictionaries, randomly select 10 of those dictionaries. In Swift, zip()
, map()
and prefix()
cover everything except the randomization. You need something like a shuffle method for the array.
Here is one that does the Fisher-Yates (fast and uniform) shuffle:
extension CollectionType {
func shuffle() -> [Generator.Element] {
var result = Array(self)
if result.count > 1 {
for i in 0 ..< result.count - 1 {
let j = Int(arc4random_uniform(UInt32(result.count - i))) + i
if i != j {
swap(&result[i], &result[j])
}
}
}
return result
}
}
With shuffle()
in hand, I can solve the problem.
let allQuestions = zip(iN, nS).map {xx, yy in ["x": xx, "y": yy]}
let shuffledQuestions = allQuestions.shuffle()
let first10ShuffledQuestions = shuffledQuestions.prefix(10)
let questionsArray: [AnyObject] = Array(first10ShuffledQuestions)
The first part, zip(iN, nS).map {xx, yy in ["x": xx, "y": yy]}
creates an array of dictionaries using the key "x"
for iN
and "y"
for nS
. The next part, shuffle()
returns an array of dictionaries in a random order. The last part, prefix(10)
returns an array slice of the shuffled array containing the first 10 elements. Because prefix()
returns an array slice and not an array, use Array()
to create an array from the array slice for the final assignment to questionsArray
.
This can all be done in one line.
let questionsArray: [AnyObject] = Array(zip(iN, nS).map {xx, yy in ["x": xx, "y": yy]}.shuffle().prefix(10))
Related Topics
Format Println Output in a Table
Swift Struct with Lazy, Private Property Conforming to Protocol
Using @Discardableresult for Closures in Swift
Swift - Associated Types in Protocol with Where Clause
Xcode Build Perfect Failure -- Copenssl Not Found
C-Style Uninitialized Pointer Passing in Apple Swift
How to Cancel Firebase Setvalue While Pending for Completion (When Offline)
Using Uilexicon to Implement Autocorrect in iOS 8 Keyboard Extension
Swift, Error Exc_Breakpoint (Code=1, Subcode=0X100695474)
Xcodebuild -Exportarchive Wont Allow Me to Specify Filename