HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 任意操作可选择快速链接?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Apple提供了一个简洁的可选链接示例

class Person {
  var residence: Residence?
}

class Residence {
  var numberOfRooms = 1
}

let john = Person()

if let roomCount = john.residence?.numberOfRooms {
  println("John's residence has \(roomCount) room(s).")
} else {
  println("Unable to retrieve the number of rooms.")
}

想象一下尝试用一些算术运算来调整条件.这会导致编译器错误,因为模运算符不支持选项.

if john.residence?.numberOfRooms % 2 == 0 { 
  // compiler error: Value of optional type int? not unwrapped
  println("John has an even number of rooms")
} else {
  println("John has an odd number of rooms")
}

当然,您总是可以执行以下操作,但它缺乏可选链接的简单性和简洁性.

if let residence = john.residence {
  if residence.numberOfRooms % 2 == 0  {
    println("John has an even number of rooms")
  }else{
    println("John has an odd number of rooms")
  }
} else {
  println("John has an odd number of rooms")
}

是否有任何Swift语言功能可以提供更好的解决方案?

解决方法

我认为你所寻找的通常在函数式编程中被称为 monad.

它不能直接在swift中使用,但通过使用某些语言功能,您可以自己以通用方式实现monad. (还定义了一个漂亮的中缀运算符,使其看起来像Haskell中的monad)

快速谷歌搜索“monad swift”在https://gist.github.com/cobbal/7562875ab5bfc6f0aed6发现了一些看起来很有希望的代码

大佬总结

以上是大佬教程为你收集整理的ios – 任意操作可选择快速链接?全部内容,希望文章能够帮你解决ios – 任意操作可选择快速链接?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。