How to access the variable out of scope of `if let` in swift [closed] - swift

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I am new to swift that I would like to use the variable funcReturn out of if let scope. anyway better way for me to do it other than using var to declare the variable?
if let funcReturn = localFunction() {
print(funcReturn)
}
print(funcReturn == "local function return value")
// i think I can do something like this but I do not need to change the value of funcReturn
if var funcReturn = localFunction() {
print(funcReturn)
}
print(funcReturn == "local function return value")

if let and if var only define the new variable inside the braces that follow. That is the way the language works.
Consider this code:
func foo() {
let aVar: Int? = 3
if let bar = aVar {
// bar is defined
}
// bar is not defined.
}
The same is true with an if var:
func foo() {
let aVar: Int? = 3
if var bar = aVar {
// bar is defined
}
// bar is not defined.
}
(The compiler will tell you that your var was never mutated.) But at the "// bar is not defined." comment, the variable bar still won't exist.
As the other poster says, guard works the opposite way:
func foo() {
let aVar: Int? = 3
guard let bar = aVar else {
return
}
// bar is defined for the rest of the function.
}
guard requires that you leave the current scope if it fails. (Usually with a return, although you can also do other things like break or continue from an outer loop.

The variable will only be in scope for the function. Another way to do it is a guard statement

Related

Providing a default binding to String of an enum with rawValue type of String [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
enum Tab : String {
case front, back
}
I would like to extend any enum that has raw value type of String to have an easily accessible bindingToString. Is there a way? Probably a protocol would have to be declared on any enum with String raw value type, but I have no idea how to do that. I'm looking for something like this:
enum Tab : String, BindableToString {
case front, back
}
var tab : Tab = .front
TextField(tab.bindingToString, ...)
However, we can create a Binding<Tab> extension to create a conversion to/from String:
extension Binding where Value == Tab {
var bindingToString : Binding<String> {
.init(get: { self.wrappedValue.rawValue }, set: { v in
if let newValue = Tab.init(rawValue: v) {
self.wrappedValue = newValue
}
})
}
}
This is almost fine, but first we need to explicitly create binding to Tab and then a binding to String, and we need to define this on every enum out there.
I was hoping we could somehow generalize this further so that we don't need to define explicitly a bindingToString on every such enum that has a raw value type of String; a protocol or a generic extension would do.
A solution utilizing the RawRepresentable idea from #loremipsum based on the proxy() func:
extension Binding where Value : RawRepresentable<String> {
var bindingToString : Binding<String> {
.init {
self.wrappedValue.rawValue
} set: { value in
if let newValue = Value(rawValue: value){
self.wrappedValue = newValue
}
}
}
}

How can i import view which bring a closure with itself in SwiftUI? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Here is my code, it does not work:
struct ContainerView<MyContent: View>: View {
let myContent: () -> MyContent
#State private var myValue: String = ""
var body: some View {
myContent() { value in
myValue = value
}
}
}
I want make this logic works, when I am bringing my view as myContent to body, I want be able to bring a string value with it like in code! I am not looking for reaching my goal with other ways, the goal of this question is be able to access value like in code as clouser.
Warning: I'm not sure what the use-case of this is -- it's not clear what problem is trying to be solved here, but there's likely a better fit that trying to make something like this work. This answer, though, does solve the compilation errors presented above.
Your syntax inside body implies that you want a trailing closure on myContent, but it's not defined in the signature. This would solve the compilation error:
struct ContainerView<MyContent: View>: View {
let myContent: (#escaping (String) -> Void) -> MyContent
#State private var myValue: String = ""
var body: some View {
Text(myValue)
myContent() { value in
myValue = value
}
}
}
Call site:
ContainerView { closure in
Button("Test") {
closure("Value")
}
}

How to mute the warning of "never mutated" in Swift? [duplicate]

This question already has answers here:
Why constant constraints the property from a structure instance but not the class instance?
(2 answers)
Swift constant UIView never mutated warning
(1 answer)
UITableViewCell var "table view cell" was never mutated
(1 answer)
Closed 5 years ago.
Regarding duplicate flag: This question is different from the flagged question as I am asking about how to mute the warnings as I was not aware of the concept of Swift. The provided below answer helps me understand the very basic nature of Swift. Thus this question should not flagged as duplicate.
I have a class name Person having following variables.
private var _id:String = ""
var id:String {
get {
return _id
}
set (newId) {
_id = newId
}
}
private var _name:String = ""
var name:String {
get {
return _name
}
set (newName) {
_name = newName
}
}
private var _signedDate:Date? = nil
var signedDate:Date {
get {
return _signedDate!
}
set(newDate) {
_signedDate = newDate
}
}
These private var's are going to update with a setter.
So while creating an object for the Person class, I am writing this code.
var p1 = Person()
p1.id = "1"
p1.name = "Hemang"
array.append(p1)
Maybe later, I will update the value of signedDate with a setter.
So I should not create this object with let.
However, it's showing me this warning:
Variable 'p1' was never mutated; consider changing to 'let' constant.
How to mute this warning?
Please let me know if you need more information on this.
Because actually you don't change the Person object,
With let you can change the properties of the object. But you can't change the object it self.
So change your code to what the warning lead you.
And of course you can try before asking this question.

Set lazy var from outside without initializing [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I defined a class using a lazy var definition, where EXIFData is a struct:
struct EXIFData {
var a : String
var b : String
}
class xxx {
...
lazy var exif: EXIFData = {
...
return EXIFData(url: self.initUrl as CFURL)
}()
Now I want to assign a value to some members without executing the initial code of lazy var definition. How can I avoid it and assing an own created struct member instead like c.exif.a = newExif.a ? I'm using Swift 3.0.
Added:
I solved it this way: As part from the same class I use the needed information to assign my value within the lazy initialization. So there is only one additional "if" statement within. No need for external excess and special tricks to avoid standard initialization.
The lazy initializer won't run if you just assign a value normally before ever reading. Here's a test case:
class Class {
lazy var lazyVar: String = {
print("Lazy initializer ran")
return "Default value"
}()
}
let object = Class()
object.lazyVar = "Custom value"
print(object.lazyVar)

Comma usage in swift

#IBAction func selectedGame(segue:UIStoryboardSegue) {
if let gamePickerViewController = segue.sourceViewController as? GamePickerViewController,
selectedGame = gamePickerViewController.selectedGame {
detailLabel.text = selectedGame
game = selectedGame
}
}
Hi all, i'm following a tutorial to learn something about swift. Yesterday I found this part of code but I can not find a way to understand what it means thatcomma means. Can u pls explain me?
The comma is used to combine multiple optional bindings into one statement to avoid unnecessary nesting.
From Swift 1.2,The if let construct can now unwrap multiple optionals at once, as well as include intervening boolean conditions. This lets you express conditional control flow without unnecessary nesting.More details
For example:
var foo: Int!
var bar: String!
// Swift 1.2
if let foo = foo,bar = bar {
// foo & bar have values.
} else {
}
// before Swift 1.2
if let foo = foo {
// nesting
if let bar = bar {
// foo & bar have value.
}
}
Xcode6.3 and above support Swift1.2.