xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Swift 5.x bug All In One

Swift 5.x bug All In One

Cannot find 'const' in scope

struct CardView: View {
  // 有初始化值, 在调用函数时候传参数会覆盖默认值
  var isFaceUp: Bool = true;
  var body: some View {
    ZStack {
      // 使用局部作用域变量,提高代码复用率
      // var shape = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      // Variable 'shape' was never mutated; consider changing to 'let' constant
      const; shape = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      if(isFaceUp) {
        shape
          .stroke(lineWidth: 12)
        shape
          .fill()
          .foregroundColor(.white)
        Text("👻")
          .fontWeight(.bold)
          .font(/*@START_MENU_TOKEN@*/.largeTitle/*@END_MENU_TOKEN@*/)
      } else {
        shape
          .fill()
          .foregroundColor(.yellow)
      }
    }
  };
}

solution

let !== const


struct CardView: View {
  // 有初始化值, 在调用函数时候传参数会覆盖默认值
  var isFaceUp: Bool = true;
  var body: some View {
    ZStack {
      // 使用局部作用域变量,提高代码复用率
      // var shape = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      // Variable 'shape' was never mutated; consider changing to 'let' constant
      // ✅  swift 使用 let 声明常量 👎 💩 
      let shape = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      if(isFaceUp) {
        shape
          .stroke(lineWidth: 12)
        shape
          .fill()
          .foregroundColor(.white)
        Text("👻")
          .fontWeight(.bold)
          .font(/*@START_MENU_TOKEN@*/.largeTitle/*@END_MENU_TOKEN@*/)
      } else {
        shape
          .fill()
          .foregroundColor(.yellow)
      }
    }
  };
}

cannot assign to property: 'self' is immutable


struct CardView: View {
  // 有初始化值, 在调用函数时候传参数会覆盖默认值
  var isFaceUp: Bool = true;
  var body: some View {
    ZStack {
      // 使用局部作用域变量,提高代码复用率
      // var shape = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      // Variable 'shape' was never mutated; consider changing to 'let' constant
      // let shape = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      // 类型推断,不需要显式的声明
      let shape: RoundedRectangle = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      if(isFaceUp) {
        shape
          .stroke(lineWidth: 12)
        shape
          .fill()
          .foregroundColor(.white)
        Text("👻")
          .fontWeight(.bold)
          .font(/*@START_MENU_TOKEN@*/.largeTitle/*@END_MENU_TOKEN@*/)
      } else {
        shape
          .fill()
          .foregroundColor(.yellow)
      }
    }
    .onTapGesture(perform: {
      let const = 666;
      print("perform \(const)");
      self.isFaceUp = !self.isFaceUp;
    })
    // 最后的一个 label 参数可以省略,简写
    // .onTapGesture {
    //   let const = 666;
    //   print("perform \(const)");
    // }
  };
}

SwiftUI’s views should be structs, which means they are immutable by default

SwiftUI 的视图应该是结构体,这意味着它们默认是不可变的

If this were our own code we could mark methods using mutating to tell Swift they will change values, but we can’t do that in SwiftUI because it uses a computed property.

如果这是我们自己的代码,我们可以使用 mutating 标记方法来告诉 Swift 它们会改变值,但我们不能在 SwiftUI 中这样做,因为它使用计算属性。

If you want to change a property’s value while your program runs, you should mark it using @State, like this: @State private var runCount = 0

如果您想在程序运行时更改属性的值,您应该使用 @State 标记它,如下所示: @State private var runCount = 0

For more complex properties, such as reference types or values that are shared across multiple views, you should use @StateObject, @ObservedObject or @EnvironmentObject instead.

https://www.hackingwithswift.com/quick-start/swiftui/how-to-fix-cannot-assign-to-property-self-is-immutable

public

Swift 为代码中的实体提供了四种不同的访问级别:public、internal、fileprivate、private。


struct CardView: View {
  // 有初始化值, 在调用函数时候传参数会覆盖默认值
  // var isFaceUp: Bool = true;
  // 需要使用 @State 才可以修改值; SwiftUI 默认 struct 是不可变的,不可以直接修改
  // @State public var isFaceUp: Bool = true;
  @State var isFaceUp: Bool = true;
  var body: some View {
    ZStack {
      // 使用局部作用域变量,提高代码复用率
      // var shape = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      // Variable 'shape' was never mutated; consider changing to 'let' constant
      // let shape = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      // 类型推断,不需要显式的声明
      let shape: RoundedRectangle = RoundedRectangle(cornerRadius: /*@START_MENU_TOKEN@*/25.0/*@END_MENU_TOKEN@*/);
      if(isFaceUp) {
        shape
          .stroke(lineWidth: 12)
        shape
          .fill()
          .foregroundColor(.white)
        Text("👻")
          .fontWeight(.bold)
          .font(/*@START_MENU_TOKEN@*/.largeTitle/*@END_MENU_TOKEN@*/)
      } else {
        shape
          .fill()
          .foregroundColor(.yellow)
      }
    }
    .onTapGesture(perform: {
      let const = 666;
      print("perform \(const)");
      // self !== this
      // self.isFaceUp = !self.isFaceUp;
      isFaceUp = !isFaceUp;
    })
    // 最后的一个 label 参数可以省略,简写
    // .onTapGesture {
    //   let const = 666;
    //   print("perform \(const)");
    // }
  };
}


Cannot use instance member 'defaultEmojiCount' within property initializer; property initializers run before 'self' is available


struct MyContentView: View {
  let defaultEmojiCount = 6;
  @State var emojiCount = defaultEmojiCount;
  let emojis = ["😃", "😃", "🐻", "🍔", "⚽","🦍","🦊","🦌","🦏","🦇","🦅","🦆","🦉","🦎","🦈","🦐","🦑","🦋","🥀","🦓","🦒","🦔","🦕","🦖","🦗","🐉","🐲","🌵","🎄","🌲","🌳","🌴","🌱","🌿","☘","🍀","🎍","🎋","🍃","🍂","🍁","🌾","🌺","🌻","🌹","🌷","🌼","🌸","💐","🍄","🌰","🎃","🐚"];
  var body: some View {
    VStack {
      HStack {
        // struct ForEach<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable
        // 动态数组范围,使用 id 防止 emoji 重复导致报错
        ForEach (emojis[0..<emojiCount], id: \.self) { emoji in
          CardView(content: emoji);
        }
      }
      Spacer()
      HStack {
        // 按钮
        Button (
          action: {
            if(emojiCount > 1) {
              emojiCount -= 1;
            }
            print("remove \(emojiCount)");
          }, label: {
            // 系统字体 icon
            Image(systemName: "minus.circle");
          }
        )
        Spacer()
        Button (
          action: {
            if(emojiCount < emojis.count) {
              emojiCount += 1;
            }
            print("add \(emojiCount)");
          }, label: {
            // 系统字体 icon
            Image(systemName: "plus.circle");
          }
        )
      }.font(.largeTitle)
    }
    .padding(.horizontal)
    .foregroundColor(.red)
  };
}



https://stackoverflow.com/questions/68533137/cannot-use-instance-member-videoname-within-property-initializer-property-ini

swiftui foreach index

Array.indices


struct MyContentView: View {
  // ...
  var body: some View {
    // view builder
    VStack {
      HStack {
        // id 重复 bug ❌
        // ForEach (emojis[0..<emojiCount], id: \.self) { emoji in
        //   CardView(content: emoji);
        // }
        // fix id 重复 bug ✅ Array.indices
        ForEach (emojis[0..<emojiCount].indices, id: \.self) { index in
          CardView(content: emojis[index]);
        }
      }
    }
  };
}

Array.enumerated

let array = ["Fred", "Astaire", "Ginger", "Rogers"]

for (index,item) in array.enumerated() {
  print(index,item)
}

https://stackoverflow.com/questions/57244713/get-index-in-foreach-in-swiftui

https://developer.apple.com/forums/thread/118361

https://www.hackingwithswift.com/forums/swiftui/accessing-the-index-in-foreach/1334\

refs

https://docs.swift.org/swift-book/GuidedTour/GuidedTour.html

https://github.com/xgqfrms/Awesome-SwiftUI-iOS-App/blob/main/src/2022/ContentView.swift

YouTube x Stanford University CS193

CS193p - Developing Apps for iOS

SwiftUI
Swift

https://cs193p.sites.stanford.edu/



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-28 15:21  xgqfrms  阅读(261)  评论(7编辑  收藏  举报