AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-1233894

user1233894's questions

Martin Hope
user1233894
Asked: 2024-12-15 09:33:33 +0800 CST

尝试从全局函数传递值

  • 6

我正在尝试从另一个视图调用的函数传递 Double 值,并且该函数在 AlamoFire 请求完成之前返回一个值

struct GetPrice {

    static func getThePrice(book: String) async -> Double? {
        
        var theNetPrice: Double = 0.0
        var iListPrice = ""
        let url = "https://example.com"
        
        let headers: HTTPHeaders = [
            "accept": "application/xml",
            "Authorization": "Basic \xxx",
           
            "Content-Type": "application/x-www-form-urlencoded"
        ]

        let body: [String: Any] = ["xxxxx"]

        AF.request(url, method: .post, parameters: body, encoding: URLEncoding.default, headers: headers)
            .responseData { response in
            var statusCode = response.response?.statusCode
                //print("response.result ", response.result)
            switch response.result {
            case .success:
                let data = response.data
                let s = String(data: data!, encoding: .utf8)
                let xml = XMLHash.parse(String(s!))
                
                    iListPrice = xml["xxx"].element!.text
                    theNetPrice = Double(iListPrice)
                    print(theNetPrice) // this shows correct value
                    //return theNetPrice -- this would give error 'Cannot convert value of type 'Double' to closure result type 'Void''
            case .failure(let error):
                statusCode = error._code
                print("status code is: \(String(describing: statusCode))")
                
                print(error)
            }
        }
        
        return theNetPrice //returns 0.0
    }
}
'''
asynchronous
  • 1 个回答
  • 33 Views
Martin Hope
user1233894
Asked: 2024-11-16 10:55:46 +0800 CST

连续运行 3 个函数,每个函数在前一个函数完成时运行

  • 6

我尝试连续运行 3 个函数,让每个函数在下一个函数开始之前完成。下面的代码运行正常,但我收到三条警告try await [one, two, three]:

  1. try表达式中没有调用抛出函数
  2. 表达式async中没有发生任何运算await
  3. 类型表达式[()]未使用。

关于如何正确编码且不出现这些警告,有什么建议吗?

Task {
    let one: () = await func1()
    let two: ()  = await func2()
    let three: ()  = await func3()
    try await [one, two, three]
}

func func1() async { ... }
func func2() async { ... }
func func3() async { ... }

这些函数本质上是从单独的外部源解码 JSON 数据,然后对结果进行计算,因此每次解码在下一次解码开始之前进行非常重要。

swift
  • 2 个回答
  • 62 Views
Martin Hope
user1233894
Asked: 2024-10-20 08:21:17 +0800 CST

尝试解码可以是字符串或整数的 JSON 值

  • 7

尝试解码可以是字符串或整数的 JSON 值“edition”,并找到此解决方案如何解码可以是字符串或整数的 JSON 值,这给了我一个错误“候选人要求'SavedFavBooksFromISBN.Edition'符合'PersistentModel'(要求指定为'Value':'PersistentModel')”

有人能帮忙解码这个可以是字符串或整数的值吗?

代码如下

import Foundation
import SwiftData

struct Response: Decodable {

    let bookObjects: [SavedFavBooksFromISBN]
}

@Model class SavedFavBooksFromISBN: Decodable, Identifiable, Hashable {

    private(set) var id: String
    private(set) var title: String
    private(set) var language: String?
    private(set) var edition: Edition
    
    init(id: String, edition: Edition, language: String?, title: String) {
        
        self.id = id
        self.title = title
        self.language = language
        self.edition = edition
    }
        
    enum Edition: Decodable {
        case int(Int)
        case string(String)
    }
    
    enum CodingKeys: String, CodingKey {
        case id = "isbn13"
        case title
        case language
        case edition
    }
    
    required init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        title = try container.decode(String.self, forKey: .title).trunc(length: 1500)
        id = try container.decode(String.self, forKey: .id)
        language = try container.decodeIfPresent(String.self, forKey: .language)
        if let value = try? container.decode(Int.self, forKey: .edition) {
            self.edition = .int(value)
        } else if let value = try? container.decode(String.self, forKey: .edition) {
            self.edition = .string(value)
        } else {
            let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Unable to decode value for `edition`")
            throw DecodingError.typeMismatch(Edition.self, context)
        }
    } //end init
}

struct BookDataStore: Decodable {

    var books: [SavedFavBooksFromISBN]
}
json
  • 1 个回答
  • 57 Views
Martin Hope
user1233894
Asked: 2024-10-03 10:58:58 +0800 CST

从 JSON 字符串中提取值

  • 4

我正在尝试从 JSON 字符串中提取 tax_amount 的值,但是这一行

let taxAmountS = json["tax_amount"] as? String

触发错误。打印 json(json 字符串)看起来应该可以工作,如下所示

["client_secret": pi_3Q5hYZHbqLi, "tax_amount": 192, "total": 2424]

它包含“tax_amount”:192。有人可以帮忙从 json 字符串中提取 192 的值吗?

let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
            guard let data = data,
                let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
                //let taxAmountS = json["tax_amount"] as? String,
                let self = self else {
                    print("Error")
                return
            }
            
            print("json is ", json)
            
            taxAmt = (taxAmountS as NSString).doubleValue
json
  • 2 个回答
  • 43 Views
Martin Hope
user1233894
Asked: 2024-09-19 04:49:02 +0800 CST

尝试根据设备类型 iPhone 与 iPad 设置图像动画的起始位置

  • 5

我试图将图像从右向左移动以制作动画,但无法弄清楚如何根据设备类型(iPad 和 iPhone)更改起始位置和结束位置。我无法在视图内设置 xpos 和 ypos 作为起始位置,否则我会收到“Type () 无法符合 View”错误,因此我将代码移动到 .onAppear,它根据设备类型设置 xpos 和 ypos,但此代码在起始位置已设置后执行。代码如下

import Foundation
import SwiftUI

struct Home1View: View {

    @State var xpos: CGFloat = 350
    @State var ypos: CGFloat = 450

    @State var opac: Double = 1.0
    @State var dHeight: Int = 0
    let layoutProperties:LayoutProperties
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                ResponsiveView {properties in
                    VStack{
                        Text("XXXX")
                        
                
                Image("number-one")
                    .resizable()
                    .frame(width: layoutProperties.dimensValues.frameSz, height: layoutProperties.dimensValues.frameSz)
                    .position(x: xpos, y: ypos)
                    .opacity(opac)
                 
                    .onAppear {
                        //ipad 13in width = 1032 height 870
                        print("display height on appear = ", geometry.size.height)
                        print("display width on appear = ", geometry.size.width)
                        xpos = geometry.size.width - 100
                        ypos = geometry.size.height - 150
                        
                        withAnimation(Animation.easeInOut(duration: 3).repeatCount(2, autoreverses: false)) {
                            xpos = 100
                            //.position(x: layoutProperties.dimensValues.xpos, y: layoutProperties.dimensValues.ypos-250)
                        } completion: {
                            opac = 0.0
                        }
                    }
            } //end ZStack
        } //end geometry
    }
}
animation
  • 1 个回答
  • 29 Views
Martin Hope
user1233894
Asked: 2024-09-14 21:47:23 +0800 CST

后端集成 Stripe 支付的 Node.JS 文件中出现错误

  • 5

我在 server.js Node 文件中的这一行出现错误 - “const determination = await stripe.tax.calculations.create({", 错误是“await 仅在异步函数中有效”。下面是我的 server.js 文件的代码

const stripe = require('stripe')('sk_test_');
const express = require('express');
const app = express();

app.use(express.json());

const calculation = await stripe.tax.calculations.create({
  currency: 'usd',
  line_items: [
    {
      amount: 1000,
      reference: 'L1',
      tax_code: 'txcd_99999999',
    },
  ],
  customer_details: {
    address: {
      line1: '920 5th Ave',
      city: 'Seattle',
      state: 'WA',
      postal_code: '98104',
      country: 'US',
    },
    address_source: 'shipping',
  },
});

app.post('/prepare-payment-sheet', async (req, res) => {
try {
    const customer = await stripe.customers.create();
    const ephemeralKey = await stripe.ephemeralKeys.create({customer: customer.id},
                                                           {apiVersion: '2024-06-20; payment_intent_with_tax_api_beta=v1;'});
    const paymentIntent = await stripe.paymentIntents.create({
        amount: 1099,
        currency: 'usd',
        customer: customer.id,
        automatic_payment_methods: {
            enabled: true,
        },
        async_workflows: {
            inputs: {
                tax: {
                calculation: '{{CALCULATION_ID}}',
                },
            },
        },
    });
    
    console.log(req.body)
    console.log(res.body)
    
    res.json({
        paymentIntentID: paymentIntent.id,
        clientSecret: paymentIntent.client_secret,
        ephemeralKey: ephemeralKey.secret,
        customer: customer.id,
        publishableKey: 'pk_test_'
    });
} catch(e) {
    res.status(400).json({ error: { message: e.message }});
}
});

app.post('/update-payment-sheet', async (req, res) => {

    const paymentIntent = await stripe.paymentIntents.update(
        req.body.paymentIntentID,
        {
            amount: req.body.amount,
        }
    );
    console.log(req.body)
    console.log(res.body)
    
    res.json({});
});

app.listen(3000, () => console.log('Running now on port 3000'));
app.get('/', (req,res) => res.json('My API is running'))

以下是 Stripe 网站上无效的代码副本

// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
const stripe = require('stripe')(
  'sk_test_',
  {apiVersion: '2024-06-20; payment_intent_with_tax_api_beta=v1;'}
);

const paymentIntent = await stripe.paymentIntents.create({
  amount: 1000,
  currency: 'usd',
  automatic_payment_methods: {
    enabled: true,
  },
  async_workflows: {
    inputs: {
      tax: {
        calculation: '{{CALCULATION_ID}}',
      },
    },
  },
});
node.js
  • 1 个回答
  • 28 Views
Martin Hope
user1233894
Asked: 2024-08-13 10:09:44 +0800 CST

类型“[ListB]”的值没有成员“books”错误

  • 6

我在下面的 func 中的“books = hardfictList.books”行中收到错误“类型为‘[ListB]’的值没有成员‘books’”

func fetchAPIDataTop100FHC() {
        
        let url = myUrl
              AF.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil, interceptor: nil)
                .response{ resp in
                    switch resp.result{
                    case .success(let data):
                        do{
                            let jsonData = try JSONDecoder().decode(NYTTop100FictionModel.self, from: data!)
                             let hardfictList = jsonData.results.listsb.filter ({ $0.listNameEncoded == "hardcover-fiction" })
                            //print(jsonData.results.listsb)
                            books = hardfictList.books
                        } catch {
                            print(String(describing: error))
                        }
                    case .failure(let error):
                        print(String(describing: error))
                    }
                } //end response

        } //end fetch API

下面是结构 ListB 和 Book 的代码

struct Result: Decodable {
  let bestsellersDate: String
  let publishedDate: String
  let publishedDateDescription: String
  let previousPublishedDate: String
  let nextPublishedDate: String
  let listsb: [ListB]

  private enum CodingKeys: String, CodingKey {
    case bestsellersDate = "bestsellers_date"
    case publishedDate = "published_date"
    case publishedDateDescription = "published_date_description"
    case previousPublishedDate = "previous_published_date"
    case nextPublishedDate = "next_published_date"
    case listsb = "lists"
  }

  init(bestsellersDate: String, publishedDate: String, publishedDateDescription: String, previousPublishedDate: String, nextPublishedDate: String, listsb: [ListB]) {
    self.bestsellersDate = bestsellersDate
    self.publishedDate = publishedDate
    self.publishedDateDescription = publishedDateDescription
    self.previousPublishedDate = previousPublishedDate
    self.nextPublishedDate = nextPublishedDate
    self.listsb = listsb
  }
}

struct ListB: Decodable {
//struct ListB: Codable {
  let listID: Int
  let listName: String
  let listNameEncoded: String
  let displayName: String
  let updated: String
  //let listImage: Any?
  //let listImageWidth: Any?
  //let listImageHeight: Any?
  let books: [Book]

  private enum CodingKeys: String, CodingKey {
    case listID = "list_id"
    case listName = "list_name"
    case listNameEncoded = "list_name_encoded"
    case displayName = "display_name"
    case updated
    //case listImage = "list_image"
    //case listImageWidth = "list_image_width"
    //case listImageHeight = "list_image_height"
    case books
  }

    init(listID: Int, listName: String, listNameEncoded: String, displayName: String, updated: String, books: [Book]) {
  //init(listID: Int, listName: String, listNameEncoded: String, displayName: String, updated: String, listImage: Any?, listImageWidth: Any?, listImageHeight: Any?, books: [Book]) {
    self.listID = listID
    self.listName = listName
    self.listNameEncoded = listNameEncoded
    self.displayName = displayName
    self.updated = updated
    //self.listImage = listImage
    //self.listImageWidth = listImageWidth
    //self.listImageHeight = listImageHeight
    self.books = books
  }
}

struct Book: Codable, Identifiable {
    let id = UUID()
  let ageGroup: String
  let amazonProductURL: URL
  let articleChapterLink: String
  let author: String
  let bookImage: URL?
  let bookImageWidth: Int?
  let bookImageHeight: Int?
  let bookReviewLink: String
  let bookUri: URL
  let btrn: String
  let contributor: String
  let contributorNote: String
  let createdDate: String
  let description: String
  let firstChapterLink: String
  let price: String
  let primaryIsbn10: String
  let primaryIsbn13: String
  let publisher: String
  let rank: Int
  let rankLastWeek: Int
  let sundayReviewLink: String
  let title: String
  let updatedDate: String
  let weeksOnList: Int
  let buyLinks: [BuyLink]

  private enum CodingKeys: String, CodingKey {
    case ageGroup = "age_group"
    case amazonProductURL = "amazon_product_url"
    case articleChapterLink = "article_chapter_link"
    case author
    case bookImage = "book_image"
    case bookImageWidth = "book_image_width"
    case bookImageHeight = "book_image_height"
    case bookReviewLink = "book_review_link"
    case bookUri = "book_uri"
    case btrn
    case contributor
    case contributorNote = "contributor_note"
    case createdDate = "created_date"
    case description
    case firstChapterLink = "first_chapter_link"
    case price
    case primaryIsbn10 = "primary_isbn10"
    case primaryIsbn13 = "primary_isbn13"
    case publisher
    case rank
    case rankLastWeek = "rank_last_week"
    case sundayReviewLink = "sunday_review_link"
    case title
    case updatedDate = "updated_date"
    case weeksOnList = "weeks_on_list"
    case buyLinks = "buy_links"
  }

  init(ageGroup: String, amazonProductURL: URL, articleChapterLink: String, author: String, bookImage: URL?, bookImageWidth: Int?, bookImageHeight: Int?, bookReviewLink: String, bookUri: URL, btrn: String, contributor: String, contributorNote: String, createdDate: String, description: String, firstChapterLink: String, price: String, primaryIsbn10: String, primaryIsbn13: String, publisher: String, rank: Int, rankLastWeek: Int, sundayReviewLink: String, title: String, updatedDate: String, weeksOnList: Int, buyLinks: [BuyLink]) {
    self.ageGroup = ageGroup
    self.amazonProductURL = amazonProductURL
    self.articleChapterLink = articleChapterLink
    self.author = author
    self.bookImage = bookImage
    self.bookImageWidth = bookImageWidth
    self.bookImageHeight = bookImageHeight
    self.bookReviewLink = bookReviewLink
    self.bookUri = bookUri
    self.btrn = btrn
    self.contributor = contributor
    self.contributorNote = contributorNote
    self.createdDate = createdDate
    self.description = description
    self.firstChapterLink = firstChapterLink
    self.price = price
    self.primaryIsbn10 = primaryIsbn10
    self.primaryIsbn13 = primaryIsbn13
    self.publisher = publisher
    self.rank = rank
    self.rankLastWeek = rankLastWeek
    self.sundayReviewLink = sundayReviewLink
    self.title = title
    self.updatedDate = updatedDate
    self.weeksOnList = weeksOnList
    self.buyLinks = buyLinks
  }
}
'''
arrays
  • 1 个回答
  • 22 Views
Martin Hope
user1233894
Asked: 2024-08-04 02:35:14 +0800 CST

尝试通过大于某个值的 Int 来过滤列表

  • 5

尝试按评级 > 1 过滤图书列表并收到错误 - 闭包参数列表的上下文类型需要 1 个参数,不能隐式忽略 - 在线 List(savedFavBooks.filter({$0.rating > 1})) {

完整代码如下

import SwiftUI
import Combine
import SwiftData

struct SavedFavoriteBookView: View {
    
    @Query private var savedFavBooks: [Book]
    @Environment(\.modelContext) private var context
    let skyPurple = Color(red: 161 / 255, green: 160 / 255, blue: 248 / 255)
    var body: some View {
        //List{
        List(savedFavBooks.filter({$0.rating > 1})) {
            ForEach(savedFavBooks) { book in
                SavedFavBookCard(bookSavedObject: book)
                    .listRowBackground(Color(red: 255 / 255, green: 221 / 255, blue: 249 / 255) .opacity(0))
                    .navigationBarTitleDisplayMode(.inline)
            }
            .onDelete(perform: delete(indexSet:))
        }

和图书代码

//  Book.swift

import Foundation
import SwiftData

struct Result: Decodable {

    let bookObjects: [Book]
}

@Model

class Book: Decodable, Identifiable, Hashable {
    let id: String
    let title: String
    let authors: [String]
    let imageURL: URL
    let subjects: [String]?
    let date_published: String
    let synopsis : String?
    var rating: Int = 0
    
    init(id: String, title: String, subjects: [String], synopsis: String, authors: [String], date_published: String, imageURL: URL, rating: Int) {
    //init(id: String, title: String, subjects: [String], authors: [String], date_published: String, imageURL: URL, rating: Int) {
        self.id = id
        self.title = title
        self.subjects = subjects
        self.authors = authors
        self.date_published = date_published
        self.synopsis = synopsis
        self.imageURL = imageURL
        self.rating = rating
    }
    
    enum CodingKeys: String, CodingKey {
        case id = "isbn"
        case title
        case date_published
        case authors
        case image
        case subjects
        case synopsis
    }
    
    required init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        date_published = try container.decode(String.self, forKey: .date_published)
        title = try container.decode(String.self, forKey: .title).trunc(length: 100)
        id = try container.decode(String.self, forKey: .id)
        authors = try container.decode(Array.self, forKey: .authors)
        subjects = try container.decodeIfPresent(Array.self, forKey: .subjects)
        synopsis = try container.decodeIfPresent(String.self, forKey: .synopsis)
        imageURL = try container.decode(URL.self, forKey: .image)
    } //end init
}

struct BookDataStore: Decodable {

//struct BookDataStore {
    var books: [Book]
}
swift
  • 1 个回答
  • 26 Views
Martin Hope
user1233894
Asked: 2024-08-01 23:03:54 +0800 CST

在数组中搜索字符串的一部分

  • 5

以下代码可以很好地按作者过滤书籍,但仅当搜索字符串等于完整字符串时才有效。示例:作者包含全名,例如["Jack Nicklaus", "Arnold Palmer", "Sam Snead"]

如何允许搜索栏根据名称的一部分进行过滤而不区分大小写,例如“Nicklaus”

var filteredBooksByAuthor: [Book] {
    if searchTextAuthor.isEmpty {
        books
    } else {
        books.filter { $0.authors.contains(searchTextAuthor) }
    }
}
arrays
  • 2 个回答
  • 44 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve