How does stringByReplacingCharactersInRange work in swift? [duplicate] - nsstring

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")

Related

How to find an element in vector of Option<String> [duplicate]

This question already has answers here:
Converting from Option<String> to Option<&str>
(5 answers)
Closed 1 year ago.
As a rust newbie I have a problem finding an element in a vector of Option using the "find" function:
#[derive(Debug)]
struct MyStruct {
name: Option<String>,
data: Option<String>
}
fn main() {
let my_vec=vec![
MyStruct{
name:Some(String::from("name1")),
data:Some(String::from("data1"))
},
MyStruct{
name:Some(String::from("name2")),
data:Some(String::from("data2"))
}
];
let search_string = String::from("name2");
let found_record=my_vec.iter().find(|s| s.name == Some(search_string));
println!("{:?}", found_record);
}
This code does not compile because of the comparison s.name == Some(search_string) because of a missing Copy trait. What would be the correct way for the "find" expression?
One option is to convert both your search_string and struct field to Option<&str> for comparison:
let found_record = my_vec.iter().find(
|s| s.name.as_deref() == Some(search_string.as_ref()));
playground
The Error cause
Note that you are constructing an Option by using Some() inside the closure by moving the String.
Some solutions
You can avoid that moving and make the closure capture by immutable reference by constructing the Option before it, as follows
let search_string = Some(String::from("name2"));
let found_record=my_vec.iter().find( |s| s.name == search_string);
Or enter inside the Option, as follows
let search_string = String::from("name2");
let found_record=my_vec.iter().find(
|s| match &s.name{Some(name)=> name, _ => return false,} == &search_string
);
I don't prefer the approach
let found_record = my_vec.iter().find(
|s| s.name.as_deref() == Some(search_string.as_ref()));
because it makes a new Some() every iteration unless if there is an optimization by the compiler.

How do you extract a value out of a golang map[string] string thats typed with interface{} [duplicate]

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"]

Golang - struct : time.Time [duplicate]

This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 6 years ago.
I am trying to cast a value to a struct which has a type of time.Time.
The value is:
t := time.Now()
format := "2006-01-02 15:04:05"
Then I am trying to put this into the struct:
response.SetAppData[0].LiveDate = time.Parse(format, t.String())
However I get the error of:
controllers/apps.go:1085: multiple-value time.Parse() in single-value context
I am not sure what I am doing wrong.
Thanks
It means that time.Parse returns two results time.Time and error values. You are assigning only to one variable.
You should do that:
response.SetAppData[0].LiveDate, err = time.Parse(format, t.String())
if err != nil {
// error handling here
}

Swift: How do I print out the value of a dictionary key inside a string expression? [duplicate]

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")
}

How to create multidimensional array in swift? [duplicate]

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]]

Resources