You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跟随RxSwift教程编译报错:Attribute仅适用于类型而非声明

Fixing the "Attribute can only be applied to types, not declarations" Error in RxSwift Tutorial's Lock.swift

Hey there, sorry to hear you hit this compile roadblock with the RxSwift tutorial—let’s break down how to fix it quickly. This error almost always stems from a mismatch between the tutorial’s outdated sample code and newer versions of Swift/RxSwift, where attribute usage rules have gotten stricter.

Here are two reliable solutions:

Older RayWenderlich tutorials often target specific RxSwift versions that align with the Swift syntax used at the time. Newer RxSwift releases (especially post-5.x) have updated internal code like Lock.swift that breaks compatibility with old sample code.

  • Open your Podfile and replace the generic RxSwift/RxCocoa lines with a version that matches the tutorial’s era. For example, if the tutorial was published around 2019-2020, use:
    pod 'RxSwift', '~> 5.1.1'
    pod 'RxCocoa', '~> 5.1.1'
    
  • Run these commands in your terminal to refresh dependencies:
    pod deintegrate
    pod install
    

This will pull the exact RxSwift version the tutorial was built for, eliminating the attribute syntax mismatch.

Solution 2: Manually Fix the Lock.swift Error

If you want to use the latest RxSwift version instead, you can patch the Lock.swift file directly. The error occurs because an attribute (like @_fixed_layout) is applied to a property/method instead of the type itself.

  • Navigate to Pods > RxSwift > Sources > RxSwift > Lock.swift in your project navigator.
  • Find the line throwing the error. It’ll look something like this (old syntax):
    class Lock {
        @_fixed_layout
        private var _lock = os_unfair_lock_s()
        // ... rest of the code
    }
    
  • Move the attribute to the class declaration instead of the property:
    @_fixed_layout
    class Lock {
        private var _lock = os_unfair_lock_s()
        // ... rest of the code
    }
    
  • Clean your project (Cmd+Shift+K) and recompile.

I totally get the frustration of outdated tutorials—they’re a pain when you’re trying to learn! Either of these steps should get your project up and running.

内容的提问来源于stack exchange,提问作者Nikita Vlasenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:27:10