GVKun编程网logo

我如何在 Swift 5 中使用协议函数参数使用相关类型的协议即 .pickerStyle()

2

本文将为您提供关于我如何在Swift5中使用协议函数参数使用相关类型的协议即.pickerStyle()的详细介绍,同时,我们还将为您提供关于iOSSwift应用程序随机EXC_BAD_ACCESS崩

本文将为您提供关于我如何在 Swift 5 中使用协议函数参数使用相关类型的协议即 .pickerStyle()的详细介绍,同时,我们还将为您提供关于iOS Swift 应用程序随机 EXC_BAD_ACCESS 崩溃:swift_bridgeObjectRetain swift_retain swift::RefCounts、Swift 新手,无法手动将 swift 2 转换为 swift 5、Swift 无法从 Swift.X 转换为 Swift.X.Type、Swift! Swift! Swift! 重要的事情说3遍!的实用信息。

本文目录一览:

我如何在 Swift 5 中使用协议函数参数使用相关类型的协议即 .pickerStyle()

我如何在 Swift 5 中使用协议函数参数使用相关类型的协议即 .pickerStyle()

如何解决我如何在 Swift 5 中使用协议函数参数使用相关类型的协议即 .pickerStyle()

我正在使用 SwiftUI 并希望根据选择器中的项目数量设置视图的选择器样式。对于少数项目,SegmentedPickerStyle() 是理想的,WheelPickerStyle() 越多越好。

library(tidyverse)
library(dplyr)
library(ggplot2)
library(gganimate)
library(ggstance)
library(zoo)
library(gifski)
library(shadowtext)

stats <- read_csv(url("https://raw.githubusercontent.com/samhoppen/Fantasy-Evaluator/main/Data/Animation%20Test%20Data.csv")) %>% 
  mutate(unique_id = paste0(player_name,recent_team))
all_weeks <- read_csv(url("https://raw.githubusercontent.com/samhoppen/Fantasy-Evaluator/main/Data/Animation%20Weeks%20Data.csv"))

NFL_pri <- stats$team_color
names(NFL_pri) <- stats$unique_id
NFL_sec <- stats$team_color2
names(NFL_sec) <- stats$unique_id

rb_ani <- ggplot(data = stats,aes(group = player_name)) +
  geom_colh(aes(x = tot_fpts,y = rank,color = unique_id,fill = unique_id),position = ''identity'',size = 2,width = 0.8) + 
  scale_x_continuous(expand = expansion(mult = c(0,0.05))) +
  scale_y_reverse(expand = expansion(mult = c(0.01,0.01)))+
  geom_shadowtext(aes(x = name_loc,label = player_name,color = unique_id),bg.color = ''white'',size = 5.5,na.rm = T,bg.r = 0.075,show.legend = FALSE) +
  scale_color_manual(values = NFL_sec)+
  scale_fill_manual(values = NFL_pri)+ 
  labs(title = "Highest-scoring Fantasy Running Backs of the Past Decade",subtitle = paste0("{all_weeks$week_name[as.numeric(prevIoUs_state)]}"),caption = "figure: @SamHoppen | Data: @nflfastR",y = "",x = "Total Fantasy Points")+
  theme(legend.position = "none",plot.title = element_text(size = 24,face = "bold",margin = margin(0,10,0)),plot.subtitle = element_text(size = 12,plot.caption = element_text(size = 12)) +
  transition_states(states = week_order,transition_length = 2,state_length = 1,wrap = F) +
  view_follow(fixed_y = TRUE) +
  enter_fly(y_loc = -21) +
  exit_fly(y_loc = -21) +
  ease_aes(''linear'')

anim <- animate(rb_ani,nframes = 100,fps = 5,renderer = gifski_renderer(),height = 900,width = 1600)

函数签名如下: 我学到的 }.pickerStyle(productsObserver.product.productFamilies?.count ?? 0 < 5 ? SegmentedPickerStyle() : WheelPickerStyle()) 在函数签名中使用泛型,因为 PickerStyle 使用关联类型。

问题不应该那么难,可能也不是 - 协议应该像这样简单 = 一样工作,但我看不到它。 非常感谢任何帮助!

解决方法

pickerStyle 是一种通用方法,它接受符合 PickerStyle 的具体类型(在编译时)。因此,它不能是 SegmentedPickerStyleWheelPickerStyle(在运行时确定)——它必须是其中之一。

因此,一个建议是创建一个视图修饰符并有条件地应用选择器样式。这里的关键区别在于它返回 _ConditionalContent<TrueContent,FalseContent> 类型的条件视图。

struct PickerStyleOption<P1: PickerStyle,P2: PickerStyle>: ViewModifier {
    let predicate: () -> Bool
    let style1: P1
    let style2: P2
    
    @ViewBuilder
    func body(content: Content) -> some View {
        if predicate() {
            content
                .pickerStyle(style1)
        } else {
            content
                .pickerStyle(style2)
        }
    }
}

为方便起见,您可以创建一个扩展:

extension View {
    func pickerStyleOption<P1: PickerStyle,P2: PickerStyle>(
            _ condition: @autoclosure @escaping () -> Bool,then style1: P1,else style2: P2) -> some View {

        self.modifier(
            PickerStyleOption(predicate: condition,style1: style1,style2: style2)
        )
    }
}

并像这样使用它:

Picker(...) {
   ...
}
.pickerStyleOption((productsObserver.product.productFamilies?.count ?? 0) < 5,then: SegmentedPickerStyle(),else: WheelPickerStyle())

iOS Swift 应用程序随机 EXC_BAD_ACCESS 崩溃:swift_bridgeObjectRetain swift_retain swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>

iOS Swift 应用程序随机 EXC_BAD_ACCESS 崩溃:swift_bridgeObjectRetain swift_retain swift::RefCounts

如何解决iOS Swift 应用程序随机 EXC_BAD_ACCESS 崩溃:swift_bridgeObjectRetain swift_retain swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>

我不断收到来自随机用户的随机崩溃报告。不幸的是,我无法定期重现这一点。用户说崩溃是在 discussionViewController 中随机发生的。所有崩溃报告都有类似的内容:

0   libswiftCore.dylib              0x00000001a53face4 swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1> >::incrementSlow(swift::RefCountBitsT<(swift::RefCountInlinedness)1>,unsigned int) + 60 (atomic:1003)
1   libswiftCore.dylib              0x00000001a53c59e0 swift_retain + 124 (RefCount.h:813)
2   libswiftCore.dylib              0x00000001a5401d60 swift_bridgeObjectRetain + 56 (SwiftObject.mm:585)
3   APPNAME                             0x0000000102b59734 closure #1 in discussionViewController.fetchPostData() + 7916

这是完整的崩溃日志和崩溃的线程:

Hardware Model:      iphone11,6
Process:             APPNAME [11770]
Path:                /private/var/containers/Bundle/Application/.../APPNAME.app/APPNAME
Identifier:          ----
Version:             62 (62)
AppStoretools:       12E262
AppVariant:          1:iphone11,6:13
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           ---- [1824]


Date/Time:           2021-06-17 12:07:01.4346 +1000
Launch Time:         2021-06-17 12:06:56.4993 +1000
OS Version:          iPhone OS 14.6 (18F72)
Release Type:        User
Baseband Version:    3.04.01
Report Version:      104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x8000000000000010 -> 0x0000000000000010 (possible pointer authentication failure)
VM Region Info: 0x10 is not in any region.  Bytes before following region: 4339515376
      REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      UNUSED SPACE AT START
--->  
      __TEXT                   102a7c000-102a94000 [   96K] r-x/r-x SM=COW  ...APPNAME.app/APPNAME

Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL,Code 0xb
Terminating Process: exc handler [11770]
Triggered by Thread:  3


Thread 3 name:
Thread 3 Crashed:
0   libswiftCore.dylib              0x00000001a53face4 swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1> >::incrementSlow(swift::RefCountBitsT<(swift::RefCountInlinedness)1>,unsigned int) + 60 (atomic:1003)
1   libswiftCore.dylib              0x00000001a53c59e0 swift_retain + 124 (RefCount.h:813)
2   libswiftCore.dylib              0x00000001a5401d60 swift_bridgeObjectRetain + 56 (SwiftObject.mm:585)
3   APPNAME                             0x0000000102b59734 closure #1 in discussionViewController.fetchPostData() + 7916
4   APPNAME                             0x0000000102ad09d4 thunk for @escaping @callee_guaranteed (@guaranteed Data?,@guaranteed NSURLResponse?,@guaranteed Error?) -> () + 132 (<compiler-generated>:0)
5   CFNetwork                       0x00000001a1b0a3dc __40-[__NSURLSessionLocal taskForClassInfo:]_block_invoke + 540 (LocalSession.mm:687)
6   CFNetwork                       0x00000001a1b1c768 __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke + 244 (LocalSessionTask.mm:584)
7   libdispatch.dylib               0x00000001a10d1a84 _dispatch_call_block_and_release + 32 (init.c:1466)
8   libdispatch.dylib               0x00000001a10d381c _dispatch_client_callout + 20 (object.m:559)
9   libdispatch.dylib               0x00000001a10db004 _dispatch_lane_serial_drain + 620 (inline_internal.h:2557)
10  libdispatch.dylib               0x00000001a10dbc34 _dispatch_lane_invoke + 456 (queue.c:3862)
11  libdispatch.dylib               0x00000001a10e64bc _dispatch_workloop_worker_thread + 764 (queue.c:6589)
12  libsystem_pthread.dylib         0x00000001ed04a7a4 0x1ed047000 + 14244
13  libsystem_pthread.dylib         0x00000001ed05174c 0x1ed047000 + 42828

我已验证 discussionViewController.fetchPostData() 不会强制解开任何可选选项,没有 try! 并且在任何地方都使用 [weak self]self?。该函数非常大,所以我很难缩小崩溃发生的范围。

Swift 新手,无法手动将 swift 2 转换为 swift 5

Swift 新手,无法手动将 swift 2 转换为 swift 5

如何解决Swift 新手,无法手动将 swift 2 转换为 swift 5

我年轻的时候经常搞砸,我构建了一个应用程序,我目前正在尝试修复并改进该应用程序,但是我在将 swift 2 转换为 swift 5 时遇到了一些问题,并且该应用程序不会成功编译

问题 1: 无法将 ''(NSError) -> ()'' 类型的值转换为预期的参数类型 ''((Error) -> Void)?''

参考这两行代码:

  1. }) { (error:NSError) in
  2. print(error.localizedDescription)

问题 2: Any 类型的值没有下标

参考这些行:

  1. key = snapshot.key
  2. itemRef = snapshot.ref
  3. if let shareContent = snapshot.value!["content"] as? [[String:Any]] {
  4. content = shareContent
  5. }
  6. else{
  7. content = ""
  8. }
  9. if let shareUser = snapshot.value!["addedByUser"] as? [[String:Any]] {
  10. addedByUser = shareUser
  11. }else{
  12. content = ""

问题 3: 表达类型不明确,没有更多上下文

  1. FIRAuth.auth()?.signInWithEmail("",password: "",completion: { (user:FIRUser?,error:NSError?) in
  2. if error == nil {
  3. print(user?.email)

如果有人可以帮助其中任何一个,我将非常感激

解决方法

问题 1) 和 3):不要注释类型,在 Swift 3+ 中,错误已成为符合 Error 的类型

  1. }) { error in
  2. print(error.localizedDescription)

关于 3) 在 Firebase 文档中查找正确的类型,它不再是 (FIRUser?,NSError?)

问题 2):在 Swift 3+ 中,编译器必须知道任何下标对象的静态类型。如果 value 应该是字典,你必须有条件地向下转换它

  1. if let sharedValue = snapshot.value as? [String:Any],let shareContent = sharedValue["content"] as? [[String:Any]] {
  2. content = shareContent
  3. }

Swift 无法从 Swift.X 转换为 Swift.X.Type

Swift 无法从 Swift.X 转换为 Swift.X.Type

你得到的错误

编译器给了我上面的例子“无法转换''Int32.Type类型的值?''到指定类型 ''Int32''"

是因为您在 Int32.self 中将 T 作为 KeyValuePairs 作为参数传递给您的函数,因此 T? 本身的返回类型变为 Int32.Type? .因此,当您尝试将其分配给 x 类型的 Int32 时,编译器会抛出错误,因为转换将失败。

所以为了解决这个问题,你可以更喜欢下面的代码:

数组扩展:

extension Array {
    func AtIndex(index: Int) -> Any {
        return self[index];
    }

    func AtIndexT<T>(index: KeyValuePairs<Int,T.Type>) -> T? {
        if let _record = index.first {
            let _key : T = self[_record.key] as! T;
            return _key;        
        } else {
            return nil;
        }
    }
}

用法:

let x:Int32? = Int(db.valueByKey(key:["integer_tgc":Int32.self]).AtIndexT(index: [2:Int32.self]))

注意: xOptional Int32 类型。

Swift! Swift! Swift! 重要的事情说3遍!

Swift! Swift! Swift! 重要的事情说3遍!

Swift正式开源,支持的平台包括Linux。


跟踪学习记录

今天的关于我如何在 Swift 5 中使用协议函数参数使用相关类型的协议即 .pickerStyle()的分享已经结束,谢谢您的关注,如果想了解更多关于iOS Swift 应用程序随机 EXC_BAD_ACCESS 崩溃:swift_bridgeObjectRetain swift_retain swift::RefCounts、Swift 新手,无法手动将 swift 2 转换为 swift 5、Swift 无法从 Swift.X 转换为 Swift.X.Type、Swift! Swift! Swift! 重要的事情说3遍!的相关知识,请在本站进行查询。

本文标签: