标签: swift-extensions

"Int"类型的不可变值只有名为adjust的变异成员

我现在正在学习Swift语言.

在Apple的文档中,我看到了一个扩展示例:

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
7.simpleDescription
Run Code Online (Sandbox Code Playgroud)

所以我就是adjust()这样说的:

7.adjust()
Run Code Online (Sandbox Code Playgroud)

它抛出一个错误:

Immutable value of type `Int` only has mutating members named adjust.
Run Code Online (Sandbox Code Playgroud)

迅速错误

我不确定导致错误的原因是什么?任何人都可以帮我理解这个问题吗?

ios swift swift-extensions

2
推荐指数
1
解决办法
1774
查看次数

Swift中的扩展功能,扩展静态功能和扩展类功能有什么区别?

我试图在UIColor上创建一个扩展函数,该函数可以采用Card.Colour类型的参数并将UIColor返回给调用方。

button.backgroundColor = UIColor.getColour(cardColour: cardToDeal.colour)


extension UIColor {
    func getColour(cardColour: Card.Colour) -> UIColor {
        switch cardColour {
        case .Red:
            return UIColor.red
        case .Green:
            return UIColor.green
        case .Blue:
            return UIColor.blue
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试执行此操作时,UIColor.getColour的扩展功能要求我在扩展方法中输入UIColor类型的参数,而不是Card.Colour的指定类型。

但是,当我将getColour的扩展功能更改为:

static func getColour(cardColour: Card.Colour) -> UIColor {
class func getColour(cardColour: Card.Colour) -> UIColor {
Run Code Online (Sandbox Code Playgroud)

它允许我传递Card.Colour类型的参数

为什么是这样?为什么将函数更改为静态函数或类函数会更改需要传入的类型?

提前致谢!

(详细的答案将不胜感激)

swift swift-extensions

2
推荐指数
1
解决办法
403
查看次数

Element == StringProtocol 和 Element: StringProtocol 有什么区别?

我不断看到如何扩展数组的不同语法。这是我看到的两个。有人能解释一下有什么区别吗?

extension Array where Element == StringProtocol {
    func foo(){}
}

extension Array where Element:StringProtocol {
    func foo(){}
}
Run Code Online (Sandbox Code Playgroud)

那么有什么区别呢?

奖金:

我正在尝试编写一个[String]与 和一起使用的扩展[Substring],并且建议我将其基于StringProtocol,因此如上所述。但是,如果我尝试做如下的事情......

func foo(separator:Character)

    for line in self{

        let components = line.split(separator: separator, maxSplits: 1, omittingEmptySubsequences: false)

        let prefix = components[0].replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) // Only trim the end of the prefix
        let suffix = components.count > 1
            ? components[1].trimmingCharacters(in: .whitespaces) // Perform full trim on the suffix
            : nil
        ... …
Run Code Online (Sandbox Code Playgroud)

swift swift-extensions swift4

2
推荐指数
1
解决办法
1298
查看次数

Swift 3通用扩展参数

在Swift 2.x中,我有一个很好的小设置,允许我使用枚举成员存储和检索字典值:

public enum UserDefaultsKey : String {
    case mainWindowFrame
    case selectedTabIndex
    case recentSearches
}

extension Dictionary where Key : String {
    public subscript(key: UserDefaultsKey) -> Value? {
        get { return self[key.rawValue] }
        set { self[key.rawValue] = newValue }
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许我访问这样的值:

let dict = userDefaults.dictionaryForKey("SearchPrefs")
if let recentSearches = dict?[.recentSearches] as? [String] {
    // Populate "Recent" menu items
}
Run Code Online (Sandbox Code Playgroud)

...而不是必须访问这样的值:

let dict = userDefaults.dictionaryForKey("SearchPrefs")
if let recentSearches = dict?[UserDefaultsKey.recentSearches.rawValue] as? [String] {
    // Populate "Recent" menu items
}
Run Code Online (Sandbox Code Playgroud)

注意: …

generics dictionary swift swift-extensions swift3

1
推荐指数
1
解决办法
2997
查看次数

具有等式元素的数组的 Swift 扩展无法调用索引(的 :)

我试图在 Swift 中为 Array 类型添加一个扩展,仅限于其元素符合 equatable 协议的数组。我试图以下列方式定义一个函数:

import Foundation

extension Array where Iterator.Element: Equatable {

    func deletedIndicies<T: Equatable>(newArray: [T]) -> [Int] {

        var indicies = [Int]()

        for element in self {

              if newArray.index(of: element) == nil {

                     indicies.append(self.index(of: element)!)
              }
        }

        return indicies
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该函数的目的是返回原始数组中没有出现在newArray.

我在 Xcode 中收到的错误是:无法使用类型为 '(of: Element)' 的参数列表调用 'index'

因为我只为元素可相等的数组定义函数,并且要求 的元素是newArray可相等的,所以我不确定为什么我不能调用索引方法。

arrays swift swift-extensions

1
推荐指数
1
解决办法
1983
查看次数

Swift 3:将UIButton扩展添加到ViewController

我是iOS / Swift的初学者,试图创建一个没有Storyboard的简单应用程序。我创建了一个UIButton扩展,我想在视图中添加一个简单的按钮(稍后将设置约束)。不幸的是,该按钮不可见。如果有人帮助我,我将不胜感激。谢谢!

--- Buttons.swift-

extension UIButton {

func createRectangleButton(buttonPositionX: Double, buttonPositionY: Double ,buttonWidth: Double, buttonHeight: Double, buttonTilte: String) {
    let button = UIButton(type: .system) as UIButton
    button.frame = CGRect(x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight)
    button.setTitle(buttonTilte, for: .normal)
    button.backgroundColor = COLOR_WHITE
    button.tintColor = COLOR_BLACK
    }   
}
Run Code Online (Sandbox Code Playgroud)

-InitialViewController.swift-

import UIKit 

class InitialViewController: BaseViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Gradient Layer
    view.addGradientBackground(colorTop: COLOR_ROYALRED2, colorBottom: COLOR_ROYALRED1)

    // Button
    let startButton = UIButton()
    startButton.createRectangleButton(buttonPositionX: 50, buttonPositionY: 20, buttonWidth: …
Run Code Online (Sandbox Code Playgroud)

uibutton ios swift-extensions swift3

1
推荐指数
1
解决办法
3757
查看次数

为什么我们使用扩展?

由于我们有面向对象编程,因此我们可以创建具有所有子类所需的所有功能的父类。那么扩展的目的是什么?我对这个问题有点困惑,请任何人帮助我。

swift swift-extensions

1
推荐指数
1
解决办法
5943
查看次数

swift中的可选协议方法,不使用@objc

在swift中使用@objc,我们可以在协议中创建一个可选方法

@objc protocol MyProtocol {
  @objc optional func anOptionalMethod()
}
Run Code Online (Sandbox Code Playgroud)

但是如何在不使用@objc的情况下创建可选的协议方法?

methods protocols optional swift swift-extensions

0
推荐指数
1
解决办法
4151
查看次数