Finding sum of elements in Swift array

This is the easiest/shortest method I can find. Swift 3 and Swift 4: let multiples = […] let sum = multiples.reduce(0, +) print(“Sum of Array is : “, sum) Swift 2: let multiples = […] sum = multiples.reduce(0, combine: +) Some more info: This uses Array’s reduce method (documentation here), which allows you to “reduce … Read more

Difference between List and Array types in Kotlin

Arrays and lists (represented by List<T> and its subtype MutableList<T>) have many differences, here are the most significant ones: Array<T> is a class with known implementation: it’s a sequential fixed-size memory region storing the items (and on JVM it is represented by Java array). List<T> and MutableList<T> are interfaces which have different implementations: ArrayList<T>, LinkedList<T> … Read more

Print array elements on separate lines in Bash?

Try doing this : $ printf ‘%s\n’ “${my_array[@]}” The difference between $@ and $*: Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed. Quoted, “$@” expands each element as a separate argument, while “$*” expands to the args merged into one argument: “$1c$2c…” (where c is the … Read more

React proptype array with shape

You can use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf(): // an array of a particular shape. ReactComponent.propTypes = { arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({ color: React.PropTypes.string.isRequired, fontSize: React.PropTypes.number.isRequired, })).isRequired, } See the Prop Validation section of the documentation. UPDATE As of react v15.5, using React.PropTypes is deprecated and the standalone package prop-types should be used instead : // … Read more

How to remove an element from an array in Swift

The let keyword is for declaring constants that can’t be changed. If you want to modify a variable you should use var instead, e.g: var animals = [“cats”, “dogs”, “chimps”, “moose”] animals.remove(at: 2) //[“cats”, “dogs”, “moose”] A non-mutating alternative that will keep the original collection unchanged is to use filter to create a new collection … Read more

How do I shuffle an array in Swift?

This answer details how to shuffle with a fast and uniform algorithm (Fisher-Yates) in Swift 4.2+ and how to add the same feature in the various previous versions of Swift. The naming and behavior for each Swift version matches the mutating and nonmutating sorting methods for that version. Swift 4.2+ shuffle and shuffled are native … Read more

Correct way to initialize empty slice

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.16). You also have the option to leave it with a nil value: var myslice []int As written in the Golang.org blog: a nil slice is functionally equivalent to a zero-length slice, even though … Read more