我现在正在学习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)

我不确定导致错误的原因是什么?任何人都可以帮我理解这个问题吗?
我试图在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类型的参数
为什么是这样?为什么将函数更改为静态函数或类函数会更改需要传入的类型?
提前致谢!
(详细的答案将不胜感激)
我不断看到如何扩展数组的不同语法。这是我看到的两个。有人能解释一下有什么区别吗?
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 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)
注意: …
我试图在 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可相等的,所以我不确定为什么我不能调用索引方法。
我是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) 由于我们有面向对象编程,因此我们可以创建具有所有子类所需的所有功能的父类。那么扩展的目的是什么?我对这个问题有点困惑,请任何人帮助我。
在swift中使用@objc,我们可以在协议中创建一个可选方法
@objc protocol MyProtocol {
@objc optional func anOptionalMethod()
}
Run Code Online (Sandbox Code Playgroud)
但是如何在不使用@objc的情况下创建可选的协议方法?