将可选值安全地分配给 var 的函数,或者如果为 nil 则分配默认值:无法将类型 'Swift.Int' 的值转换为 'Swift.String'

Function to safely assign an optional to a var, or assign default if nil: Could not cast value of type 'Swift.Int' to 'Swift.String'

你好!


。 .我又一次崩溃了寻求帮助——希望这段代码+任何可能的答案对社区有所帮助。

。 .所以我正在尝试制作一种允许我安全地将可选值分配给 lhs 的方法,例如:

var cool_variable = risky_optional!

而不必中断它所在的任何范围的流程.. 这样做的目的是减少控制语句,并且不会在强制解包时立即使程序崩溃(我花了很多时间试图设计好的不自然执行此操作的代码)。

。 .起初,我以为我已经成功了,因为一切都很完美......然后在我的第四轮测试中,我得到了

Could not cast value of type 'Swift.Int' (0x105c52190) to 'Swift.String' (0x105c584d8).

。 .我花了很多时间尝试重构和返工,但我意识到我对泛型、Any 和可选项的理解还不具体——尽管我确实学习和实践,但我时不时地尝试做一些行不通的事情。

代码如下:


>> 这是 func 的屏幕截图,在 XCODE 中非常漂亮,如果你喜欢的话 <<

>> And here is the implementation in XCODE <<

/** 
    Safely assign the lhs to this call--the value of [=12=]?, or a default.
    - Don't include ? or ! in the parameter
*/
func safeAssign <ReturnType> (value_to_return: ReturnType?)
 -> ReturnType  {

    // Ensure safety
    guard value_to_return != nil 
    else {

        // Entry: found nil
        print ("SA() -> 1  : SR: [=12=] was nil! Can't assign to lhs")

        // -Value is irrelevant at this point
        // -switch (value_to_return) would be confusing
        let type = value_to_return

        switch ( type ) {

         case is Int?:
            print("SA() -> 2.1: assigning lhs to default Int >0<")
            return 0 as! ReturnType

         case is String?:
            print("SA() -> 2.2: assigning lhs to default String")
            return "" as! ReturnType

         default:
            // In case our switch breaks, we will know why it crashes
            print("SA() -> 2.0: No cases found--RTE incoming")

        }//switch/>

        // Should force crash, but at least I'll know exactly why
        return type!

    }//guard/>

    // Let's get out of here safely ;)
    print("SA() -> Exit: Successfully Assigned lhs to \(value_to_return!)")
    return value_to_return!

}//safeAssign/>

//---------
// Testing:
//--------

// Optional for test 1-2
var int_opty : Int? = 5

// Soon to be safe-assigned
var zizzle = 0

// Safe assign to 5
print ("\n SA Test 1:")
zizzle = safeAssign(int_opty)

// Will cause a non-safe-assignment to force unwrap nil
int_opty = nil

// Safely assign to default value, instead of unwrapping nil
print ("\n SA Test2:")
 zizzle = safeAssign(int_opty)
  print(">>>>>>>>>> Zizzle is \(zizzle)")

// Optional for test 3-4
var str_opty : String? = "five"

// Soon to be safe-assigned
var zazzle = "zero"

// Safe assign to 5
print ("\n SA Test 3:")
 zazzle = safeAssign(str_opty)

// Will cause a non-safe-assignment to force unwrap nil
str_opty = nil

// Safely assign to default value, instead of unwrapping nil
print ("\n SA Test 4:")
 zazzle = safeAssign(str_opty)
  print ("3: Zazzle is \(zazzle)")

输出:

 SA Test 1:
SR -> Exit: Successfully Assigned lhs to 5

 SA Test2:
SR -> 1  : SR: [=13=] was nil! Can't assign to lhs
SR -> 2.1: assigning lhs to default Int >0<
>>>>>>>>>> Zizzle is 0

 SA Test 3:
SR -> Exit: Successfully Assigned lhs to five

 SA Test 4:
SR -> 1  : SR: [=13=] was nil! Can't assign to lhs
SR -> 2.1: assigning lhs to default Int >0<
Could not cast value of type 'Swift.Int' (0x105c52190) to 'Swift.String' (0x105c584d8).

。 .所以我看到它挂在哪里,尝试用 If / Guard 语句替换 switch,用 Any、Optional<> 和其他一些无处可去的方法尝试......我无法让它工作,并且觉得我就我对 Swift

的了解而言,此时我正敲打着键盘

。 .我真的不需要这种方法,(因为我想成为一名优秀的设计师,哈哈),但是节省一点空白总是好的,如果我在我的大部分作业中使用它,那么应该会出现一个小错误稍后,它可能会自行纠正(比如在 while 循环或更新周期中)而不是使程序崩溃。

。 .那,即使我确定 Try/Catch 的东西可以工作......我想弄清楚为什么 this 不会 运行 所以我可以学习并成为更好的编码员。

非常感谢。

平安与祝福! -流体

实际上你不需要一个方法,只需要:

zazzle = str_opty ?? ""

简单!

我真的不知道为什么你的方法无法完成这项工作。但我认为最好切换 ReturnType.self:

switch ReturnType.self {

case is Int.Type:
    print("SR -> 2.1: assigning lhs to default Int >0<")
    return 0 as! ReturnType

case is String.Type:
    print("SR -> 2.2: assigning lhs to default String")
    return "" as! ReturnType

default:
    // In case our switch breaks, we will know why it crashes
    print("SR -> 2.0: No cases found--RTE incoming")

}

编辑:

我现在知道为什么你的方法不起作用了!考虑以下代码

func f<T>(x: T?) {
    print(x is Bool?)
    print(x is Int?)
    print(x is NSNumberFormatter?)
    print(x is NSURLSessionDelegate?)
}

let a: String? = nil
f(a)

猜猜它打印了什么?

true
true
true
true

似乎 nil is 每个可选类型,无论它是结构、class 还是协议。如果您考虑一下,这实际上是有道理的。 nil 可以分配给任何可选类型,对吗?