我是靠谱客的博主 眼睛大小兔子,这篇文章主要介绍Designed for Safety,现在分享给大家,希望可以做个参考。

Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and integers are checked for overflow, memory is automatically managed, and enforcement of exclusive access to memory guards against many programming mistakes. Syntax is tuned to make it easy to define your intent — for example, simple three-character keywords define a variable ( var ) or constant ( let ). And Swift heavily leverages value types, especially for commonly used types like Arrays and Dictionaries. This means that when you make a copy of something with that type, you know it won’t be modified elsewhere.

Another safety feature is that by default Swift objects can never be nil. In fact, the Swift compiler will stop you from trying to make or use a nil object with a compile-time error. This makes writing code much cleaner and safer, and prevents a huge category of runtime crashes in your apps. However, there are cases where nil is valid and appropriate. For these situations Swift has an innovative feature known as optionals. An optional may contain nil, but Swift syntax forces you to safely deal with it using the ? syntax to indicate to the compiler you understand the behavior and will handle it safely.

extension Collection where Element == Player {
// Returns the highest score of all the players,
// or nil if the collection is empty.
func highestScoringPlayer() -> Player? {
return self.max(by: { $0.highScore < $1.highScore })
}
}

Use optionals when you might have an instance to return from a function, or you might not.

if let bestPlayer = players.highestScoringPlayer() {
recordHolder = “”"
The record holder is (bestPlayer.name),
with a high score of (bestPlayer.highScore)!
“”"
} else {
recordHolder = “No games have been played yet.”)
}
print(recordHolder)
// The record holder is Erin, with a high score of 271!

let highestScore = players.highestScoringPlayer()?.highScore ?? 0
// highestScore == 271

Features such as optional binding, optional chaining, and nil coalescing let you work safely and efficiently with optional values.

最后

以上就是眼睛大小兔子最近收集整理的关于Designed for Safety的全部内容,更多相关Designed内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部