How can i import view which bring a closure with itself in SwiftUI? [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 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")
}
}

Related

Initialize swift/swiftui var with 3 conditions [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 7 months ago.
Improve this question
I am trying to initialize a var with a couple of conditions
struct BreadCrumbCard: View {
var selection:String
var isSelected: Bool
var color = Color("Gray")
if(isSelected){ //error is here
color = Color("Yellow")
}else if(!selection.isEmpty){
color = Color("Green")
}else{
color = Color("Gray")
}
var body: some View{
...
"Expected declaration"
I've been searching for some time now but I can't find a way to do this or an alternative, I'm sure this must be obvious but I am new to swift. How can I initialize this variable with these conditions?
You can't put control code in a struct's or class's top-level scope, it must always be placed inside a function or similar context.
There's several ways to solve this problem, one way would be to use a computed property:
struct BreadCrumbCard: View {
var selection: String
var isSelected: Bool
var color: Color {
if isSelected { //error is here
return Color("Yellow")
} else if !selection.isEmpty {
return Color("Green")
} else {
return Color("Gray")
}
}
var body: some View{
Text("foo").foregroundColor(self.color)
}
}

How to access the variable out of scope of `if let` in swift [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 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

objectWillChange.send() how exactly does this work? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
func choose(_ card: MemoryGame<String>.Card)
{
objectWillChange.send()
model.choose(card)
}
I have some function here which is in the ViewModel for something I'm making and I just wanna know how exactly does objectWillChange work? Like when it says object what exactly is it referring to? Since I put this in the ViewModel is it saying the ViewModel will change? But then again I put it specifically into this choose function so what relevance does that have? I basically want it to publish that something changed in the model(A card got chosen) which it seems to be doing but I don't fully understand what I stated previously.
objectWillChange is a property defined on the ObservableObject protocol as you can see in the documentation of ObservableObject.
The compiler synthesises a default implementation for the property, which emits a value whenever any #Published properties of the object changes.
SwiftUI uses the objectWillChange Publisher to update the View when you store an object as #ObservedObject (or #StateObject or #EnvironmentObject) on the view.
You can also manually send updates through objectWillChange using its send() method when you need to manually update the view.
See a simplified example below:
class ViewModel: ObservableObject {
#Published var published: Int = 0
var nonPublished: Int = 0
}
struct MyView: View {
#ObservedObject var viewModel: ViewModel
...
}
let viewModel = ViewModel()
let view = MyView(viewModel: viewModel)
viewModel.published = 1 // viewModel.objectWillChange emits a value here and view will be updated
viewModel.nonPublished = 2 // viewModel.objectWillChange does not emit a value here and view will not be updated

Random Image when pressing a button 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 2 years ago.
Improve this question
I'm trying to make a random image appear on the screen, when I am pressing a button. I have three images which I want to be randomly shown, when I press the button. How do I do this?
If you are using an Array you can use the .randomElement(). Here's a simple example using the symbols from SF Symbols.
struct RandomImage: View {
#State var random: String = ""
var body: some View {
VStack {
Image(systemName: random)
Button(action: {
self.random = chooseRandomImage()
}) {
Text("Another one!")
}
}
}
}
var images = ["sun.max.fill", "moon.fill", "star.fill"]
func chooseRandomImage() -> String {
let array = images
let result = array.randomElement()!
return result
}

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)