This question already has answers here:
Multidimensional arrays in Swift
(7 answers)
Closed 8 years ago.
I'm trying to push array type object to special index inside array in new Swift lang by Apple. It should look like this = [ [...], [...], ...], as I've read in the docs - NSMutableArray type is assigned to variable automatically if it's var, but even in playground it throws me errors:
var arr = [];
arr[0] = []; // Error: cannot assign to result of this expression
arr.insert([], atIndex:0) // Error: 'NSArray' does not have member named 'insert'
var array2d: [[Int]] = [[1,2,3,4],[5,6,7,8]]
Related
This question already has an answer here:
Golang updating maps and variables in an object
(1 answer)
Closed 3 years ago.
Currently trying to learn Go.
I have the following function, but it only works when the team doesn't exist in the map already and it creates a new record in the map. It will not update the values if the team already has a struct in the map.
func AddLoss(teamMap map[string]TeamRow, teamName string) {
if val, ok := teamMap[teamName]; ok {
val.Wins++
val.GamesPlayed++
} else {
newTeamRow := TeamRow{Losses: 1}
teamMap[teamName] = newTeamRow
}
}
I have updated the function to just replace the existing record with a brand new struct with the values I want, but that seems odd that I can't update the values in a map.
Can someone explain this to me, or point me in the right direction?
You have a map of string to the value of TeamRow so when you get the val out of the map it returns the value of the team, not a pointer to the team. If you make the map a string to the pointer of TeamRow then when you get the val out it will point to the memory that is stored in the map so values will persist beyond the scope of your AddLoss function. To do this simply add a * to the map declaration - teamMap map[string]*TeamRow though when you populate it you will then also need to store pointers in the map.
This question already has an answer here:
How do I avoid unwrap when converting a vector of Options or Results to only the successful values?
(1 answer)
Closed 4 years ago.
I want some way to have such a cast when writing code like this:
struct Value;
fn remove_missed(uncertain_vector: Vec<Option<Value>>) -> Vec<Value> {
uncertain_vector
.into_iter()
.filter(|element| match element {
Some(val) => true,
None => false,
})
.collect()
}
How can I achieve this? I believe that the type implication mechanism is not smart enough to determine that the resulting collection will contain only Option<Value> where all such objects are the same in terms of their type (Value).
The compiler answers my question partially:
error[E0277]: a collection of type `std::vec::Vec<Value>` cannot be built from an iterator over elements of type `std::option::Option<Value>`
--> src/lib.rs:10:10
|
10 | .collect()
| ^^^^^^^ a collection of type `std::vec::Vec<Value>` cannot be built from `std::iter::Iterator<Item=std::option::Option<Value>>`
|
= help: the trait `std::iter::FromIterator<std::option::Option<Value>>` is not implemented for `std::vec::Vec<Value>`
You can use Iterator::flatten which creates "an iterator that flattens nested structure" – in this case, pulls out Some from Option.
let v = vec![None, None, Some(1), Some(2), None, Some(3)];
let filtered: Vec<_> = v.into_iter().flatten().collect();
Or Iterator::filter_map to filter and map the element in one go – with an equal result.
let filtered: Vec<_> = v.into_iter().filter_map(|e| e).collect();
Playground
This question already has answers here:
Explain Type Assertions in Go
(3 answers)
Accessing Nested Map of Type map[string]interface{} in Golang
(2 answers)
Typed, nested map of map[string]interface{} returns "type interface {} does not support indexing"
(1 answer)
get value form nested map type map[string]interface{}
(2 answers)
how to access nested Json key values in Golang
(3 answers)
Closed 4 years ago.
I have something like this:
x1 := someFunctionWithAnInterfaceReturnValue()
and the underlying type is something like this:
x2 := map[string] string{"hello": "world"}
How would I access value in x1?
Essentially I want the equivalent of this for x1:
var value string = x2["hello"]
Use a type assertion:
x1 := someFunctionWithAnInterfaceReturnValue()
x2, ok := x1.(map[string]string)
if !ok {
// handle unexpected type
}
var value string = x2["hello"]
This question already has answers here:
Using stringByReplacingCharactersInRange in Swift
(13 answers)
Closed 8 years ago.
I have this code in objective-c:
[textField.text stringByReplacingCharactersInRange:range withString:string];
try to convert to swift, like so:
textField.text.stringByReplacingCharactersInRange(range, withString: string)
but compiler says, Int is not identical to 'String.index'
How should I modify expression?
I am using both objective-c / swift expressions in UITextFieldDelegate method:
func textField(textField: UITextField!,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String!) -> Bool {
Use bridgeToObjectiveC()
textField.text.bridgeToObjectiveC().stringByReplacingCharactersInRange(range, withString: string)
it will more clarify
var st = "abc"
str.bridgeToObjectiveC().stringByReplacingCharactersInRange(NSMakeRange(2,1), withString:"r")
Explicit casting can also be done to NSString and it not needs bridgeToObjectiveC
var st = "abc" as NSString
let abc = st.stringByReplacingCharactersInRange(NSMakeRange(2, 3), withString: "abc")
This question already has answers here:
escape dictionary key double quotes when doing println dictionary item in Swift
(5 answers)
Closed 8 years ago.
For some reason, I just can't make this expression work:
let expandedBio: Dictionary<String,AnyObject> = ["name":"Saurabh", "profession":"developer", "language":"java", "employed": true]
if let employed : AnyObject = expandedBio["employed"] {
println("\(expandedBio[\"name\"]) is not available")
}
How do I output the println statement? I get the error
Unexpected "" character error in string interpolation
How do I do this right?
In current version of Swift you have to put value in its own constant/variable first, then use that.
if let employed : AnyObject = expandedBio["employed"] {
let t = expandedBio["name"]
println("\(t) is not available")
}