Swift difference between var arr:[String] = [] and var arr = [String]()
The first one, var arr:[String] = []
is usually used for adding values upon initialisation. You could create an empty array like this, but usually you would do the second one to create the empty array: var are = [String]()
.
Either one is acceptable, but usually you would use the first for adding values on initialisation, just like you would with normal variables: you would normally write something like this:
var exampleVariable:String = "Example String"
and to compare the second, it would be like writing:
var exampleVariable = String()
Simply, you are adding the square brackets to show you are making an array.
Swift String variable
These two are basically the same.
When you use var myVar: String = "Hello"
, you directly tell the swift compiler that your variable is type String
.
When you use var myVar = "Hello"
, you do not specify the type of your variable, so the swift compiler has do do that for you.
Usually, you can get away without declaring your variable type and just have swift do it for you. However, in some cases, namely computed properties and custom classes/structures, you must manually declare your variable to be a specific type.
In your case, either way is fine. The end result is the same, just be aware of the difference for the future.
How to convert Strings in Swift?
To get all values of your dictionary as an array you can use the values
property of the dictionary:
let dictionary: Dictionary<String, Any> = [
"key_a": "value_a",
"key_b": "value_b",
"key_c": "value_c",
"key_d": "value_d",
"key_e": 3
]
let values = Array(dictionary.values)
// values: ["value_a", "value_b", "value_c", "value_d", 3]
With filter
you can ignore all values of your dictionary that are not of type String
:
let stringValues = values.filter({ $0 is String }) as! [String]
// stringValues: ["value_a", "value_b", "value_c", "value_d"]
With map you can transform the values of stringValues
and apply your replacingOccurrences
function:
let adjustedValues = stringValues.map({ $0.replacingOccurrences(of: "value_", with: "") })
// adjustedValues: ["a", "b", "c", "d"]
Difference between various type of Variable declaration in swift
Array
is a swift type where as NSArray
is an objective C type. NS classes support dynamic-dispatch and technically are slightly slower to access than pure swift classes.
1) var arr = NSArray()
arr
is an NSArray()
here - you can re-assign things to arr
but you can't change the contents of the NSArray()
- this is a bad choice to use IMO because you've put an unusable array into the variable. I really can't think of a reason you would want to make this call.
2) var arr = NSMutableArray()
Here you have something usable. because the array is mutable you can add and remove items from it
3) var arr = Array()
This won't compile - but var arr = Array<Int>()
will.
Array takes a generic element type ( as seen below)
public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer {
/// Always zero, which is the index of the first element when non-empty.
public var startIndex: Int { get }
/// A "past-the-end" element index; the successor of the last valid
/// subscript argument.
public var endIndex: Int { get }
public subscript (index: Int) -> Element
public subscript (subRange: Range<Int>) -> ArraySlice<Element>
}
4) var arr : NSMutableArray?
You are defining an optional array here. This means that arr
starts out with a value of nil
and you an assign an array to it if you want later - or just keep it as nil. The advantage here is that in your class/struct you won't actually have to set a value for arr
in your initializer
5) var arr : NSMutableArray = []
It sounds like you are hung up on confusion about Optional values.
Optional means it could be nil or it could not
When you type something as type?
that means it is nil
unless you assign it something, and as such you have to unwrap it to access the values and work with it.
Swift - Array of Any to Array of Strings
You can't change the type of a variable once it has been declared, so you have to create another one, for example by safely mapping Any
items to String
with flatMap
:
var oldArray: [Any] = []
var newArray: [String] = oldArray.flatMap { String($0) }
How to create an empty array in Swift?
Here you go:
var yourArray = [String]()
The above also works for other types and not just strings. It's just an example.
Adding Values to It
I presume you'll eventually want to add a value to it!
yourArray.append("String Value")
Or
let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)
Add by Inserting
Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):
yourArray.insert("Hey, I'm first!", atIndex: 0)
Or you can use variables to make your insert more flexible:
let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)
You May Eventually Want to Remove Some Stuff
var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)
The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.
Removing Values Without Knowing the Index
But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?
if let indexValue = yourOtherArray.index(of: "RemoveMe") {
yourOtherArray.remove(at: indexValue)
}
This should get you started!
Split a String into an array in Swift?
The Swift way is to use the global split
function, like so:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
with Swift 2
In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters
property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).
let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)
fullNameArr[0] // First
fullNameArr[1] // Last
Related Topics
My Reachability Notifier Is Only Able to Be Called Once
How to Remove Single Object in Array from Multiple Matching Object
Array Element Checking in Swift
How to Authorize Twitter with Swifter
Skaction Works in Didmovetoview But Doesn't Works in Function
How to Turn Off Core Data Write-Ahead Logging in Swift Using Options Dictionary
How to Load Thousands Records to Realm Correctly
Swift 4: Timer Crashing - Unrecognized Selector Sent to Instance
Displaying Instances of View Controllers Within Xcode Without Disturbing the Current Hierarchy
Collectionview Flowlayout Overlapping When Scrolling Not Working
Swift Unable to Use API Data in Collection View
Check the JSON Response Is Array or Int or String for a Key
Calling Delegate Function from Appdelegate Not Working
Exception: Cannot Manually Set the Delegate on a Uinavigationbar Managed by a Controller
Get "No Keychain Available" Error When Try to Access Keychain from App Extension