gpt4 book ai didi

swift - 我应该将我的字符串设置为 Nil 还是 Empty?

转载 作者:可可西里 更新时间:2023-11-01 00:56:54 25 4
gpt4 key购买 nike

我有一个 Meeting 类,我在其中解析用户的日历以确定该类的属性。这些字段中的大多数都是 String,其中可能没有任何内容。当我发现这些字段为空时,最好将它们设置为空 "" 还是将它们设为可选并将它们设置为 nil

/**
Parses calendar entry to create a Meeting object.

- parameter calendarEvent: The calendar entry we want to parse
- returns: A Meeting Object with the relevant information extracted from the calendar entry.
*/
public static func parse(calendarEvent: EKEvent) -> Meeting {
let location = calendarEvent.location ?? ""
let description = calendarEvent.notes ?? ""

let allInput = "\(calendarEvent.title)\n\(location)\n\(description)"
let parsedHostCodes = parseHostCode(from: allInput)
let parsedPasscodes = parseParticipantCode(from: allInput, hostCodes: parsedHostCodes)
let parsedPhoneNumbers = parsePhoneNumber(from: allInput, codes: parsedPasscodes + parsedHostCodes)

return Meeting(
UUID: calendarEvent.eventIdentifier,
title: calendarEvent.title,
description: description,
location: location,
startTime: calendarEvent.startDate,
endTime: calendarEvent.endDate,
allday: calendarEvent.isAllDay,
participantCodes: parsedPasscodes,
hostcodes: parsedHostCodes,
phoneNumbers: parsedPhoneNumbers,
host: retrieveHost(from: calendarEvent.organizer),
attendees: parseParticipants(from: calendarEvent.attendees),
provider: allInput.contains(pattern: attRegex) ? .att : .unknown)
}

最佳答案

Optionals 旨在确定数据的缺失。如果那是您的程序要检查的内容,那么您真的应该使用该功能。从长远来看,在您可以利用“可选链接”和“自动展开”的情况下,这是非常值得的:

struct Event {
let location: String?
}

struct Day {
let events: [Event]?
}

var events: [Event]?
let currentDay: Day?

events = [Event(location: "conf room A1")]
currentDay = Day(events: events)

if let events = currentDay?.events {
for event in events {
if let location = event.location {
print(location)
}
}
}

这里发生的事情比您看到的要多得多。首先,我将所有内容都设为可选,因为您的代码中很可能就是这种情况。

“if let”的第一行使用了“Optional Chaining”。如果 currentDay 或 currentDay.events 为 nil,则不会执行“if” block 。如果 currentDay 和 currentDay.events 不为零,则 currentDay.events 将自动展开并分配给“events”,然后代码执行将落入“if” block 。接下来,根据当天是否有任何事件(即数组计数),“if let location = event.location”还会检查 location 是否为 nil,如果不是 nil,将自动展开并分配给“location"并将打印该值。

如果这些 Optionals 中的任何一个为 nil,那么您的代码中的任何内容都不需要更改。在这里,我删除了“events”和“currentDay”的分配,以便它们都为零:

var events: [Event]?
let currentDay: Day? = nil

if let events = currentDay?.events {
for event in events {
if let location = event.location {
print(location)
}
}
}

正如您所看到的,从长远来看,利用 Optionals 会减少维护工作并使代码总体上更简洁。

关于swift - 我应该将我的字符串设置为 Nil 还是 Empty?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45186421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com