Small Swiftly Features I Keep Forgetting - Part 1
I'm reading the Apple Swift book once again. This time the prerelease version for Swift 2.0 and I rediscover things from earlier releases of Swift I had forgotten. So, ignore this post. This is just a reference for the future me. :)
## Swift Tour
Functions can take a variable number of arguments.
func sumOf(numbers: Int...) -> Int {
return numbers.reduce(0, combine: +)
}
sumOf(1,2,3)
You can provide an explicit name in parentheses after set in a setter.
struct Person {
var name: String {
get { return self.name }
set(theNewName) { print("the new name is (theNewName)") }
}
}
var person = Person()
person.name = "Dominik"
## The Basics
You can access the minimun and maximum values of each integer type with.
let minValue = UInt8.min let maxValue = UInt8.max
## Strings and Characters
Find out whether a `String` value is empty by checking its Boolean `isEmpty` property.
let emptyString = ""
if emptyString.isEmpty {
print("It's really empty")
}
## Collection Types
Append an array of one or more compatible items with the addition assignement operator (`+=`).
var shoppingList = ["Soy Milk", "Bread"] shoppingList += ["Apples", "Bananas", "Coffee", "Creme"]
You can also use subscript syntax to change a range of values at once, even if the replacement set of values has a different length than the range you are replacing.
shoppingList[4...5] = ["Bananas", "Bananas", "More Bananas"] shoppingList
If you need the integer index of each item as well as its value, use the `enumerate()` method to interate over the array instead.
for (index, value) in shoppingList.enumerate() {
print("(index): (value)")
}
You can also initialize a set with an array literal, as shorthand way to write one or more values as a set collection.
var favoriteGenres: Set = ["Rock", "Indie", "Sing and Songwriter"]
Set: intersect(_:), intersect(_:), union(_:) and subtract(_:) .
let oddDigits: Set = [1, 3, 5, 7, 9] let evenDigits: Set = [0, 2, 4, 6, 8] let singleDigitPrimeNumbers: Set = [2, 3, 5, 7] oddDigits.union(evenDigits).sort() oddDigits.intersect(evenDigits).sort() oddDigits.subtract(singleDigitPrimeNumbers).sort() oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()
Did you find something one should mention here? Let me know.