简体   繁体   English

如何将可选链接与 nil 合并运算符一起使用?

[英]How do I use Optional Chaining with nil coalescing operator?

Using the enums and structures, implement the getArtistGenre() function.使用枚举和结构,实现 getArtistGenre() function。 Given a Song as input, return the raw value of the artist's primary genre.给定一首歌曲作为输入,返回艺术家主要流派的原始值。 If either the artist is nil or the primaryGenre is nil, then return an empty string.如果艺术家为 nil 或 primaryGenre 为 nil,则返回一个空字符串。 You must use optional chaining and the nil coalescing operator (??).您必须使用可选链接和 nil 合并运算符 (??)。

enum Genre: String {
    case country, blues, folk
}

struct Artist {
    let name: String
    var primaryGenre: Genre?
}

struct Song {
    let title: String
    let released: Int
    var artist: Artist?
}

func getArtistGenre(song: Song) -> String {
    
}

As the comments suggest:正如评论所暗示的:

func getArtistGenre(song: Song) -> String {
      return song.artist?.primaryGenre?.rawValue ?? “”
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 nil 合并运算符 '??' 的左侧具有非可选类型“字符串”,因此从不使用右侧 - Left side of nil coalescing operator '??' has non-optional type 'String', so the right side is never used 如何将OR运算符与可选绑定一起使用? - How can I use the OR operator with optional binding? 使用nil合并运算符递增值时的问题 - Issue in using nil coalescing operator for incrementing a value nil-coalescing运算符使编译器报告歧义 - nil-coalescing operator causes compiler to report ambiguity nil合并运算符'??'的左侧 具有非可选的类型'Int',因此从右侧不使用从swift 1.2转换为4后的警告 - Left side of nil coalescing operator '??' has non-optional type 'Int', so the right side is Never used Warning after Conversion from swift 1.2 to 4 如何在解开 Optional 值时意外发现 nil 中的问题? - How do I figure out the issue in unexpectedly found nil while unwrapping an Optional value? 我如何修复,在我的代码中解包 Optional 值时意外发现 nil - How do I fix ,Unexpectedly found nil while unwrapping an Optional value, in my code 使用 Combine,您如何使用 nil-coalescing 进行 flatMap - With Combine, how can you flatMap with nil-coalescing 如何在Objective-C中使用可选的协议方法? - How do I use optional protocol methods in Objective-C? 为什么会出现以下错误:“致命错误:在展开可选值时意外发现nil”? -以及如何具体修复? - Why do I get the following error: “fatal error: unexpectedly found nil while unwrapping an Optional value”? - and how can I fix it specifically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM