Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ only_rules:

- duplicate_imports

# Prefer checking `isEmpty` over comparing `count` to zero.
- empty_count

# Arguments can be omitted when matching enums with associated types if they
# are not used.
- empty_enum_arguments
Expand Down
2 changes: 1 addition & 1 deletion Modules/Sources/JetpackStats/Charts/BarChartView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ struct BarChartView: View {

@ChartContentBuilder
private var significantPointAnnotations: some ChartContent {
if tappedDataPoint == nil, let maxPoint = data.significantPoints.currentMax, data.currentData.count > 0 {
if tappedDataPoint == nil, let maxPoint = data.significantPoints.currentMax, !data.currentData.isEmpty {
PointMark(
x: .value("Date", maxPoint.date, unit: data.granularity.component, calendar: context.calendar),
y: .value("Value", maxPoint.value)
Expand Down
2 changes: 1 addition & 1 deletion Modules/Sources/JetpackStats/Charts/LineChartView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ struct LineChartView: View {

@ChartContentBuilder
private var significantPointAnnotations: some ChartContent {
if let maxPoint = data.significantPoints.currentMax, data.currentData.count > 0 {
if let maxPoint = data.significantPoints.currentMax, !data.currentData.isEmpty {
PointMark(
x: .value("Date", maxPoint.date, unit: data.granularity.component, calendar: context.calendar),
y: .value("Value", maxPoint.value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ struct SimpleBarChartView: View {

@ChartContentBuilder
private var peakAnnotation: some ChartContent {
if let maxPoint = data.currentData.max(by: { $0.value < $1.value }), data.currentData.count > 0 {
if let maxPoint = data.currentData.max(by: { $0.value < $1.value }), !data.currentData.isEmpty {
PointMark(
x: .value("Date", maxPoint.date, unit: data.granularity.component),
y: .value("Value", maxPoint.value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ struct TopListScreenView: View {

@ViewBuilder
private func listContent(data: TopListData) -> some View {
if data.items.count > 0 {
if !data.items.isEmpty {
listSection(.top10, data: data)
}
if data.items.count > 10 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ struct StatsDataAggregator {
case .sum:
normalizedData[date] = dataPoint.sum
case .average:
if dataPoint.count > 0 {
// swiftlint:disable:next empty_count
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are nine instances where the rule is bypassed.

I considered getting the agent to refactor the code so that opting out is not necessary:

  Want me to create the follow-up branch with these changes? The plan would be:

  1. Add isEmpty extension on NSSet, NSMutableArray, NSMutableOrderedSet
  2. Add isEmpty to AggregatedDataPoint and ReaderInterestsDataSource
  3. Revert the disable comments for those 5 cases, using .isEmpty instead
  4. Keep the 2 legitimate disables (AnyTermWithViewContext, tuple)

Decided not to go down that path for the moment. In particular, extending Foundation Objective-C types seems like a dead end. We should remove them in favor of Swift implementations instead.

if dataPoint.count != 0 {
normalizedData[date] = dataPoint.sum / dataPoint.count
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ struct TopListExternalLinkRowView: View {
.foregroundColor(.primary)
.lineLimit(1)

if item.children.count > 0 {
if !item.children.isEmpty {
Text(Strings.ArchiveSections.itemCount(item.children.count))
.font(.caption)
.foregroundColor(.secondary)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public class CommentsScreen: ScreenObject {
public func verifyCommentsListEmpty() -> CommentsScreen {
XCTAssertTrue(emptyImage.waitForExistence(timeout: 3))
XCTAssertTrue(app.staticTexts["Be the first to leave a comment."].isHittable)
XCTAssertTrue(app.cells.containing(.button, identifier: "reply-comment-button").count == 0)
XCTAssertTrue(app.cells.containing(.button, identifier: "reply-comment-button").isEmpty)
return self
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public enum ContentExtractor {
public static func extractRelevantText(from content: String) throws -> String {
let doc = try SwiftSoup.parse(content)

guard let body = doc.body(), body.children().count > 0 else {
guard let body = doc.body(), !body.children().isEmpty else {
return content // Return as is
}

Expand Down
2 changes: 1 addition & 1 deletion Modules/Sources/WordPressKit/JetpackScanThreat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public struct JetpackThreatContext {
}
}

return (highlights.count > 0) ? highlights : nil
return (!highlights.isEmpty) ? highlights : nil
}

/// Generates an NSRange from an array
Expand Down
4 changes: 2 additions & 2 deletions Modules/Sources/WordPressKit/JetpackThreatFixStatus.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ public struct JetpackThreatFixResponse: Decodable {
statusArray.append(fixStatus)
}

isFixingThreats = statusArray.filter { $0.status == .inProgress }.count > 0
isFixingThreats = !statusArray.filter { $0.status == .inProgress }.isEmpty
threats = statusArray
}

/// Returns true the fixing status is complete, and all threats are no longer in progress
public var finished: Bool {
return inProgress.count <= 0
return inProgress.isEmpty
}

/// Returns all the fixed threats
Expand Down
2 changes: 1 addition & 1 deletion Modules/Sources/WordPressKit/SiteDesignServiceRemote.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public struct SiteDesignRequest {
"preview_height": "\(thumbnailSize.height)" as AnyObject,
"scale": UIScreen.main.nativeScale as AnyObject
]
if 0 < groups.count {
if !groups.isEmpty {
let groups = groups.map { $0.rawValue }
parameters["group"] = groups.joined(separator: ",") as AnyObject
}
Expand Down
2 changes: 1 addition & 1 deletion Modules/Sources/WordPressKit/WordPressComRestApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ extension WordPressComRestApi {
}

var errorDictionary: AnyObject? = responseDictionary as AnyObject?
if let errorArray = responseDictionary["errors"] as? [AnyObject], errorArray.count > 0 {
if let errorArray = responseDictionary["errors"] as? [AnyObject], !errorArray.isEmpty {
errorDictionary = errorArray.first
}
guard let errorEntry = errorDictionary as? [String: AnyObject],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ open class WordPressOrgXMLRPCValidator: NSObject {
let matches = rsdURLRegExp.matches(in: html,
options: NSRegularExpression.MatchingOptions(),
range: NSRange(location: 0, length: html.count))
if matches.count <= 0 {
if matches.isEmpty {
return nil
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import WordPressSharedObjC
/// - Returns: The formatted string.
///
@objc public class func formatContentString(_ string: String, isPrivateSite isPrivate: Bool) -> String {
guard string.count > 0 else {
guard !string.isEmpty else {
return string
}

Expand All @@ -70,7 +70,7 @@ import WordPressSharedObjC
/// - Returns: The formatted string.
///
@objc public class func removeForbiddenTags(_ string: String) -> String {
guard string.count > 0 else {
guard !string.isEmpty else {
return string
}
var content = string
Expand Down Expand Up @@ -101,7 +101,7 @@ import WordPressSharedObjC
/// - Returns: The formatted string.
///
@objc public class func normalizeParagraphs(_ string: String) -> String {
guard string.count > 0 else {
guard !string.isEmpty else {
return string
}
var content = string
Expand Down Expand Up @@ -142,7 +142,7 @@ import WordPressSharedObjC
// We don't want to remove new lines from preformatted tag blocks,
// so get the ranges of such blocks.
let matches = RegEx.preTags.matches(in: content, options: .reportCompletion, range: NSRange(location: 0, length: content.count))
if matches.count == 0 {
if matches.isEmpty {

// No blocks found, so we'll parse the whole string.
ranges.append(NSRange(location: 0, length: content.count))
Expand Down Expand Up @@ -184,7 +184,7 @@ import WordPressSharedObjC
/// - Returns: The formatted string.
///
@objc public class func removeInlineStyles(_ string: String) -> String {
guard string.count > 0 else {
guard !string.isEmpty else {
return string
}
var content = string
Expand All @@ -206,7 +206,7 @@ import WordPressSharedObjC
/// - Returns: The formatted string.
///
@objc public class func resizeGalleryImageURL(_ string: String, isPrivateSite isPrivate: Bool) -> String {
guard string.count > 0 else {
guard !string.isEmpty else {
return string
}

Expand Down Expand Up @@ -282,7 +282,7 @@ import WordPressSharedObjC
/// - Returns: The formatted string.
///
@objc public class func removeTrailingBreakTags(_ string: String) -> String {
guard string.count > 0 else {
guard !string.isEmpty else {
return string
}

Expand Down
4 changes: 2 additions & 2 deletions Modules/Tests/JetpackStatsTests/MockStatsServiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ struct MockStatsServiceTests {
print("elapsed: \((CFAbsoluteTimeGetCurrent() - startTime) * 1000) ms")

// THEN
#expect(response.items.count > 0)
#expect(!response.items.isEmpty)
#expect(response.items.count <= 40, "Should return maximum 40 items")

// THEN all items are posts
Expand Down Expand Up @@ -56,6 +56,6 @@ struct MockStatsServiceTests {
print("elapsed: \((CFAbsoluteTimeGetCurrent() - startTime) * 1000) ms")

// THEN - Basic validations
#expect(response.metrics.count > 0, "Should return at least one data point")
#expect(!response.metrics.isEmpty, "Should return at least one data point")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ struct WeeklyTrendsViewModelTests {
)

// Then
#expect(viewModel.weeks.count == 0)
#expect(viewModel.weeks.isEmpty)
#expect(viewModel.maxValue == 1)
}

Expand Down Expand Up @@ -376,6 +376,6 @@ struct WeeklyTrendsViewModelTests {
)

// Then
#expect(viewModel.weeks.count == 0)
#expect(viewModel.weeks.isEmpty)
}
}
8 changes: 4 additions & 4 deletions Modules/Tests/WordPressSharedTests/LanguagesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ class LanguagesTests {
@Test func testLanguagesEffectivelyLoadJsonFile() {
let languages = WordPressComLanguageDatabase.shared

XCTAssert(languages.all.count != 0)
XCTAssert(languages.popular.count != 0)
XCTAssert(!languages.all.isEmpty)
XCTAssert(!languages.popular.isEmpty)
}

@Test func testAllLanguagesHaveValidFields() {
let languages = WordPressComLanguageDatabase.shared
let sum = languages.all + languages.popular

for language in sum {
XCTAssert(language.slug.count > 0)
XCTAssert(language.name.count > 0)
XCTAssert(!language.slug.isEmpty)
XCTAssert(!language.name.isEmpty)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ extension FancyAlertViewController {
message = NSLocalizedString("Incorrect username or password. Please try entering your login details again.", comment: "An error message shown when a user signed in with incorrect credentials.")
}

if message.trim().count == 0 {
if message.trim().isEmpty {
message = NSLocalizedString("Log in failed. Please try again.", comment: "A generic error message for a failed log in.")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ open class LoginViewController: NUXViewController, LoginFacadeDelegate {
/// You will want to set this to `true` if the error was caused after pressing a button
/// (e.g. Next button).
func displayError(message: String, moveVoiceOverFocus: Bool = false) {
guard message.count > 0 else {
guard !message.isEmpty else {
errorLabel?.isHidden = true
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ extension TwoFAViewController: ASAuthorizationControllerDelegate, ASAuthorizatio
// Some password managers(like 1P) don't deliver `rawClientDataJSON`. In those cases we need to assemble it manually.
func extractClientData(from credential: ASAuthorizationPlatformPublicKeyCredentialAssertion, challengeInfo: WebauthnChallengeInfo) -> Data? {

if credential.rawClientDataJSON.count > 0 {
if !credential.rawClientDataJSON.isEmpty {
return credential.rawClientDataJSON
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ extension SearchTableViewCell: UITextFieldDelegate {
sanitizedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
}

let hasValidEdits = sanitizedString.count > 0 || range.length > 0
let hasValidEdits = !sanitizedString.isEmpty || range.length > 0

if hasValidEdits {
guard let start = textField.position(from: textField.beginningOfDocument, offset: range.location),
Expand Down Expand Up @@ -129,7 +129,7 @@ extension SearchTableViewCell: UITextFieldDelegate {
return
}

if text.count == 0 {
if text.isEmpty {
delegate.startSearch(for: "")
} else {
delegate.startSearch(for: text)
Expand Down
4 changes: 2 additions & 2 deletions Sources/WordPressData/Swift/Blog+Lookup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ public extension Blog {
return true
}

return Blog.selfHosted(in: context)
return !Blog.selfHosted(in: context)
.filter { $0.jetpack?.isConnected == true }
.count > 0
.isEmpty
}

@objc(selfHostedInContext:)
Expand Down
6 changes: 3 additions & 3 deletions Sources/WordPressData/Swift/Post.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public class Post: AbstractPost {

let matchingCategories = blogCategories.filter({ return $0.categoryName == categoryName })

if matchingCategories.count > 0 {
if !matchingCategories.isEmpty {
newCategories = newCategories.union(matchingCategories)
}
}
Expand Down Expand Up @@ -215,7 +215,7 @@ public class Post: AbstractPost {
// MARK: - BasePost

override public func contentPreviewForDisplay() -> String {
if let excerpt = mt_excerpt, excerpt.count > 0 {
if let excerpt = mt_excerpt, !excerpt.isEmpty {
if let preview = PostPreviewCache.shared.excerpt[excerpt] {
return preview
}
Expand All @@ -240,7 +240,7 @@ public class Post: AbstractPost {
.stringByDecodingXMLCharacters()
.strippingHTML()

if title.count == 0 && !hasRemote() && contentPreviewForDisplay().count == 0 {
if title.isEmpty && !hasRemote() && contentPreviewForDisplay().isEmpty {
title = NSLocalizedString("(no title)", comment: "Lets a user know that a local draft does not have a title.")
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/WordPressData/Swift/ReaderCard+CoreDataClass.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ public class ReaderCard: NSManagedObject {
return .post
}

if topicsArray.count > 0 {
if !topicsArray.isEmpty {
return .topics
}

if sitesArray.count > 0 {
if !sitesArray.isEmpty {
return .sites
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ extension WordPressOrgRestApi {
) {
if let dotComID = blog.dotComID?.uint64Value,
let token = blog.account?.authToken,
token.count > 0 {
!token.isEmpty {
self.init(
dotComSiteID: dotComID,
bearerToken: token,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ final class MockStockPhotosService: StockPhotosService {

func search(params: StockPhotosSearchParams, completion: @escaping (StockPhotosResultsPage) -> Void) {
let text = params.text
guard text.count > 0 else {
guard !text.isEmpty else {
completion(StockPhotosResultsPage.empty())
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ final class MockTenorService: TenorService {

override func search(params: TenorSearchParams, completion: @escaping (TenorResultsPage) -> Void) {
let text = params.text
guard text.count > 0 else {
guard !text.isEmpty else {
completion(TenorResultsPage.empty())
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class DomainsServiceTests: CoreDataTestCase {

func testDomainServiceHandlesTwoNewDomains() {
let domains = findAllDomains()
XCTAssert(domains.count == 0, "Expecting no domains initially")
XCTAssert(domains.isEmpty, "Expecting no domains initially")

stubDomainsResponseWithFile("domain-service-valid-domains.json")
fetchDomains()
Expand Down
Loading