Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift中的功能_Swift_Function_Swiftui - Fatal编程技术网

Swift中的功能

Swift中的功能,swift,function,swiftui,Swift,Function,Swiftui,我试图通过构建一个非常基本的杠铃重量板计算器来学习swift——用户在文本字段中输入一个数字,它会显示所需的板 我在Swift Playgrounds中编写了一个函数,该函数在我正试图实现的情况下运行良好,但我不知道如何将其移动到应用程序视图中,在该视图中用户输入一个数字并进行过滤 我曾尝试在网上寻找对此的解释,但没有任何运气:以下是我的Swift游乐场代码,这是我理想的使用方法: import UIKit func barbellweight (weight: Int){ var p

我试图通过构建一个非常基本的杠铃重量板计算器来学习swift——用户在文本字段中输入一个数字,它会显示所需的板

我在Swift Playgrounds中编写了一个函数,该函数在我正试图实现的情况下运行良好,但我不知道如何将其移动到应用程序视图中,在该视图中用户输入一个数字并进行过滤

我曾尝试在网上寻找对此的解释,但没有任何运气:以下是我的Swift游乐场代码,这是我理想的使用方法:

import UIKit

func barbellweight (weight: Int){
    var plate_hash : [Int:Int] = [:]

    if weight == 45 {
        print("You only need the bar!")
    }else if weight < 45{
        print("Must be divisible by 5!")
    }else if (weight % 5 != 0){
           print("Must be divisible by 5!")
    }else{
        
        let plate_array = [45, 35, 25, 10, 5, 2.5]
        var one_side_weight = Double(weight - 45) / 2.0

        for plate_size in plate_array {
            var plate_amount = (one_side_weight / plate_size)
            plate_amount.round(.towardZero)
            one_side_weight -= (plate_size * plate_amount)
            plate_hash[Int(plate_size)] = Int(plate_amount)
        }
    }
    let plate_hash_filtered = plate_hash.filter { $0.value > 0 }
    //print(plate_hash_filtered)
    print(plate_hash_filtered)
}

barbellweight(weight: 225)
导入UIKit
func杠铃重量(重量:整数){
变量板散列:[Int:Int]=[:]
如果重量=45{
打印(“您只需要该栏!”)
}否则,如果重量<45{
打印(“必须可以被5整除!”)
}否则如果(重量%5!=0){
打印(“必须可以被5整除!”)
}否则{
设板_数组=[45,35,25,10,5,2.5]
var单侧重量=双倍(重量-45)/2.0
用于板阵列中的板尺寸{
可变极板数量=(单面重量/极板尺寸)
板材数量四舍五入(.towardZero)
单侧重量-=(板尺寸*板数量)
板材散列[Int(板材尺寸)]=Int(板材数量)
}
}
让plate_hash_filtered=plate_hash.filter{$0.value>0}
//打印(印版\u散列\u过滤)
打印(印版\u散列\u过滤)
}
杠铃重量(重量:225)
下面是在Swift UI中实现它的尝试,但没有任何运气。我知道它是解构的,并且有点不同——我不太明白如何将函数集成到SwiftUI中。如果有人对这个具体问题的资源有任何建议,我将非常感谢

import SwiftUI

struct Weight_Plate: View {
    @State var weight: String = "135"
    @State var plate_hash = [String]()
    @State var plate_array = [45, 35, 25, 10, 5, 2.5]
    
    
    var body: some View {
        var one_side_weight = Double(Int(weight)! - 45) / 2.0
                
        List{
            Text("Number of Plates Needed Per Side")
                .multilineTextAlignment(.center)
            ForEach(self.plate_array, id: \.self) { plate_size in
                var plate_amount = (one_side_weight / plate_size)
                if Int(weight) == 45 {
                    Text("You only need the bar!")
                } else if Int(weight)! < 45 {
                    Text("Must be divisible by 5!")
                } else if (Int(weight)! % 5 != 0) {
                       Text("Must be divisible by 5!")
                } else {
                        //Text("Error")
                        plate_amount.round(.towardZero)
                        one_side_weight -= (plate_size * plate_amount)
                    Text("\(Int(plate_size)) x \(Int(plate_amount))")
                            
                       // Text("\(plate):\(Int(plate_amount))")
            }
        }
            
        HStack(alignment: .center) {
            Text("Weight:")
                .font(.callout)
                .bold()
            TextField("Enter Desired Weight", text: $weight)
                .textFieldStyle(RoundedBorderTextFieldStyle())
        }.padding()
    }
}

}
struct Weight_Plate_Previews: PreviewProvider {
    static var previews: some View {
        Weight_Plate()
    }
}
导入快捷界面
结构重量板:视图{
@状态变量权重:String=“135”
@State var plate_hash=[String]()
@状态变量板数组=[45,35,25,10,5,2.5]
var body:一些观点{
var单侧重量=双倍(整数(重量)!-45)/2.0
名单{
文本(“每侧需要的板数”)
.multilitextalignment(.center)
ForEach(self.plate\u数组,id:\.self){plate\u大小,单位为
可变极板数量=(单面重量/极板尺寸)
如果Int(重量)==45{
文本(“您只需要该条!”)
}否则,如果整数(重量)!<45{
文本(“必须可被5整除!”)
}如果(整数(重量)!%5!=0),则为else{
文本(“必须可被5整除!”)
}否则{
//文本(“错误”)
板材数量四舍五入(.towardZero)
单侧重量-=(板尺寸*板数量)
文本(\(整块(板材尺寸))x\(整块(板材数量)))
//正文(“\(板块):\(整数(板块金额))
}
}
HStack(对齐:。中心){
文本(“权重:”)
.font(.callout)
.bold()
TextField(“输入所需重量”,文本:$Weight)
.textFieldStyle(RoundedBorderTextFieldStyle())
}.padding()
}
}
}
结构重量板预览:预览提供程序{
静态var预览:一些视图{
配重板()
}
}

我非常感谢任何对我有帮助的推荐人的帮助和建议。谢谢大家!

您知道您仍然可以定义和调用函数,对吗

将您的代码更改为此

import SwiftUI
func barbellWeight (weight: Int) -> [String] { // naming convention in Swift is camelcase
    var plate_hash = [Int: Int]()

    if weight == 45 {
        return ["You only need the bar!"]
    } else if weight < 45 {
        return ["Insufficient weight!"]
    } else if weight % 5 != 0 {
        return ["Must be divisible by 5!"]
    } else {
        let plate_array = [45, 35, 25, 10, 5, 2.5]
        var one_side_weight = Double(weight - 45) / 2.0

        for plate_size in plate_array {
            var plate_amount = (one_side_weight / plate_size)
            plate_amount.round(.towardZero)
            one_side_weight -= plate_size * plate_amount
            plate_hash[Int(plate_size)] = Int(plate_amount)
        }
    }
    
    return plate_hash.compactMap {
        if $0.value < 0 {
            return nil
        } else {
            return "\($0.key): \($0.value)"
        }
    }
    
}
    
struct Weight_Plate: View {
    @State var weight = "135"
    
    var body: some View {
        List {
            ForEach(barbellWeight(weight: Int(weight) ?? 135), id: \.self) {
                Text($0)
            }
        }
            
        HStack(alignment: .center) {
            Text("Weight:")
                .font(.callout)
                .bold()
            TextField("Enter Desired Weight", text: $weight)
                .textFieldStyle(RoundedBorderTextFieldStyle())
        }.padding()
    }
}
struct Weight_Plate_Previews: PreviewProvider {
    static var previews: some View {
        Weight_Plate()
    }
}
导入快捷界面
func barbellWeight(weight:Int)->[String]{//Swift中的命名约定为camelcase
var plate_hash=[Int:Int]()
如果重量=45{
return[“您只需要酒吧!”]
}否则,如果重量<45{
返回[“重量不足!”]
}否则,如果重量%5!=0{
return[“必须能被5整除!”]
}否则{
设板_数组=[45,35,25,10,5,2.5]
var单侧重量=双倍(重量-45)/2.0
用于板阵列中的板尺寸{
可变极板数量=(单面重量/极板尺寸)
板材数量四舍五入(.towardZero)
单侧重量-=板材尺寸*板材数量
板材散列[Int(板材尺寸)]=Int(板材数量)
}
}
返回板\u hash.compactMap{
如果$0.0的价值<0{
归零
}否则{
返回“\($0.key):\($0.value)”
}
}
}
结构重量板:视图{
@状态变量权重=“135”
var body:一些观点{
名单{
ForEach(杠铃重量(重量:Int(重量)??135),id:\.self){
文本(0美元)
}
}
HStack(对齐:。中心){
文本(“权重:”)
.font(.callout)
.bold()
TextField(“输入所需重量”,文本:$Weight)
.textFieldStyle(RoundedBorderTextFieldStyle())
}.padding()
}
}
结构重量板预览:预览提供程序{
静态var预览:一些视图{
配重板()
}
}
当然,你可以玩这个,让它看起来更好。还有其他更有效的方法,但这是可行的

编辑:您只需以通常的方式定义函数!我重写了你的函数来返回一个字符串数组,每个字符串对应一个盘子,当你运行它时,你可以看到计数对。由于权重是一个@State变量,当您通过接受用户的输入来更改它时,SwiftUI会自动重新加载依赖于该变量的任何视图。这将导致重新加载ForEach,并再次调用函数。ForEach接受一个项目数组,因此我将字典的键和值粘在一起。也许这会让事情变得明朗一点

要获得学习SwiftUI的帮助,请访问Paul Hudson的网站。这就是我如何开始学习SwiftUI以及如何过渡到UIKit的过程

避免做任何事情