repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
megavolt605/CNLDataProvider
refs/heads/master
CNLDataProvider/CNLDataViewer+UICollectionView.swift
mit
1
// // CNLDataViewer+UICollectionView.swift // CNLDataProvider // // Created by Igor Smirnov on 23/12/2016. // Copyright © 2016 Complex Numbers. All rights reserved. // import UIKit extension UICollectionView: CNLDataViewer { public var ownerViewController: UIViewController? { return parentViewController } public subscript (indexPath: IndexPath) -> CNLDataViewerCell { let identifier = cellType?(indexPath)?.cellIdentifier ?? "Cell" return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CNLDataViewerCell // swiftlint:disable:this force_cast } public subscript (cellIdentifier: String?, indexPath: IndexPath) -> CNLDataViewerCell { let identifier = cellIdentifier ?? cellType?(indexPath)?.cellIdentifier ?? "Cell" return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CNLDataViewerCell // swiftlint:disable:this force_cast } public func loadMoreCell(_ indexPath: IndexPath) -> CNLDataViewerLoadMoreCell { return dequeueReusableCell(withReuseIdentifier: "Load More Cell", for: indexPath) as! CNLDataViewerLoadMoreCell // swiftlint:disable:this force_cast } public func batchUpdates(_ updates: @escaping () -> Void) { performBatchUpdates(updates, completion: nil) } public func batchUpdates(updates: @escaping () -> Void, completion: @escaping (_ isCompleted: Bool) -> Void) { performBatchUpdates(updates, completion: completion) } public func initializeCells() { if let loadMoreeCellDataSource = self as? CNLDataViewerLoadMore { register(loadMoreeCellDataSource.loadMoreCellType, forCellWithReuseIdentifier: "Load More Cell") } //register(CNLCollectionViewLoadMoreCell.self, forCellWithReuseIdentifier: "Load More Cell") } public func selectItemAtIndexPath(_ indexPath: IndexPath, animated: Bool, scrollPosition position: CNLDataViewerScrollPosition) { selectItem(at: indexPath, animated: animated, scrollPosition: position.collectionViewScrollPosition) } public func notifyDelegateDidSelectItemAtIndexPath(_ indexPath: IndexPath) { delegate?.collectionView!(self, didSelectItemAt: indexPath) } public func selectedItemPaths() -> [IndexPath] { return selectedItemPaths() } public func scrollToIndexPath(_ indexPath: IndexPath, atScrollPosition position: CNLDataViewerScrollPosition, animated: Bool) { scrollToItem(at: indexPath, at: position.collectionViewScrollPosition, animated: animated) } func nonEmptySections() -> [Int] { return (0..<numberOfSections).filter { return self.numberOfItems(inSection: $0) > 0 } } public func scrollToTop(_ animated: Bool = true) { let sections = nonEmptySections() if let section = sections.first { scrollToItem( at: IndexPath(item: 0, section: section), at: UICollectionViewScrollPosition.top, animated: animated ) } } public func scrollToBottom(_ animated: Bool = true) { let sections = nonEmptySections() if let section = sections.last { let rowCount = numberOfItems(inSection: section) scrollToItem( at: IndexPath(item: rowCount, section: section), at: UICollectionViewScrollPosition.top, animated: true ) } } public func deselectAll(_ animated: Bool = true) { let items = (0..<numberOfSections).flatMap { section in return (0..<self.numberOfItems(inSection: section)).map { return IndexPath(item: section, section: $0) } } for item in items { deselectItem(at: item, animated: animated) } } public func reloadSections(_ sections: IndexSet, withRowAnimation animation: CNLDataViewerCellAnimation) { reloadSections(sections) } public func reloadItemsAtIndexPaths(_ indexes: [IndexPath], withAnimation animation: CNLDataViewerCellAnimation) { reloadItems(at: indexes) } public func createIndexPath(item: Int, section: Int) -> IndexPath { return IndexPath(item: item, section: section) } // Cells public func cellForItemAtIndexPath<T: CNLDataProvider>( _ dataProvider: T, cellIdentifier: String?, indexPath: IndexPath, context: CNLModelObject? ) -> AnyObject where T.ModelType.ArrayElement: CNLModelObject { if dataProvider.dataProviderVariables.isLoadMoreIndexPath(indexPath) { let cell = loadMoreCell(indexPath) cell.setupCell(self, indexPath: indexPath) let model = dataProvider.dataSource.model if model.isPagingEnabled { dataProvider.fetchNext(nil) } return cell as! UICollectionViewCell // swiftlint:disable:this force_cast } else { let cell = self[cellIdentifier, indexPath] if let item = dataProvider.itemAtIndexPath(indexPath: indexPath) { cell.setupCell(self, indexPath: indexPath, cellInfo: item, context: context) } return cell as! UICollectionViewCell // swiftlint:disable:this force_cast } } public func cellSizeForItemAtIndexPath<T: CNLDataProvider>(_ dataProvider: T, indexPath: IndexPath, context: CNLModelObject?) -> CGSize? where T.ModelType.ArrayElement: CNLModelObject { if dataProvider.dataProviderVariables.isLoadMoreIndexPath(indexPath) { return CNLCollectionViewLoadMoreCell.cellSize(self, indexPath: indexPath) } else { if let item = dataProvider.itemAtIndexPath(indexPath: indexPath) { return cellType?(indexPath)?.cellSize(self, indexPath: indexPath, cellInfo: item, context: context) } } return CGSize.zero } // Headers public func createHeader<T: CNLDataProvider>(_ dataProvider: T, section: Int) -> UIView? where T.ModelType: CNLModelArray, T.ModelType.ArrayElement: CNLModelObject { let indexPath = createIndexPath(item: 0, section: section) if let currentHeaderType = headerType?(section), let item = dataProvider.itemAtIndexPath(indexPath: indexPath) { let height = currentHeaderType.headerHeight(self, section: section, cellInfo: item) let view = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: height)) let headerText = dataProvider.sectionTextForItem(item: item) currentHeaderType.setupHeader(self, view: view, section: section, cellInfo: item, headerText: headerText) return view } return nil } public func headerHeight<T: CNLDataProvider>(_ dataProvider: T, section: Int) -> CGFloat where T.ModelType: CNLModelArray, T.ModelType.ArrayElement: CNLModelObject { let indexPath = createIndexPath(item: 0, section: section) if let currentHeaderType = headerType?(section), let item = dataProvider.itemAtIndexPath(indexPath: indexPath) { return currentHeaderType.headerHeight(self, section: section, cellInfo: item) } return 0 } } open class CNLCollectionViewLoadMoreCell: UICollectionViewCell, CNLDataViewerLoadMoreCell { open var activity: CNLDataViewerActivity? open var createActivity: () -> CNLDataViewerActivity? = { return nil } open func setupCell<T: CNLDataViewer>(_ dataViewer: T, indexPath: IndexPath) where T: UIView { contentView.backgroundColor = UIColor.clear activity = createActivity() if let activity = activity?.view { contentView.addSubview(activity) } } static open func cellSize<T: CNLDataViewer>(_ dataViewer: T, indexPath: IndexPath) -> CGSize where T: UIView { return CGSize(width: dataViewer.frame.width, height: 40) } override open func layoutSubviews() { super.layoutSubviews() // sometimes layout is called BEFORE setupCell - workaround this bug if activity != nil { let minimalDimension = min(bounds.width, bounds.height) activity!.frame.size = CGSize(width: minimalDimension, height: minimalDimension) activity!.frame.origin = CGPoint(x: bounds.midX - minimalDimension / 2.0, y: 0) if !activity!.isAnimating { activity!.startAnimating() } } } } /* class CNLCollectionViewLoadMoreCell: UICollectionViewCell, CNLDataViewerLoadMoreCell { var activity: NVActivityIndicatorView? func setupCell<T : CNLDataViewer>(_ dataViewer: T, indexPath: IndexPath) where T : UIView { activity = NVActivityIndicatorView( frame: CGRect.zero, type: NVActivityIndicatorType.randomType, color: RPUIConfig.config.basicControls.animationColor, padding: nil ) contentView.addSubview(activity) } static func cellSize<T: CNLDataViewer>(_ dataViewer: T, indexPath: IndexPath) -> CGSize where T: UIView { return CGSize(width: dataViewer.frame.width, height: 40) } override func layoutSubviews() { super.layoutSubviews() let minimalDimension = min(bounds.width, bounds.height) activity.frame.size = CGSize(width: minimalDimension, height: minimalDimension) activity.center = CGPoint(x: bounds.midX, y: minimalDimension / 2.0) if !activity.isAnimating { activity.startAnimating() } } } */
f08ec6a60c37e4510395be37df77ddba
40.65812
189
0.659828
false
false
false
false
cikelengfeng/HTTPIDL
refs/heads/master
Sources/Runtime/HTTPData.swift
mit
1
// // Data.swift // Pods // // Created by 徐 东 on 2017/8/17. // // import Foundation public struct HTTPData { public let payload: Data public let fileName: String public let mimeType: String public init(with payload: Data, fileName: String, mimeType: String) { self.payload = payload self.fileName = fileName self.mimeType = mimeType } } extension HTTPData: RequestContentConvertible { public func asRequestContent() -> RequestContent { return .data(value: payload, fileName: fileName, mimeType: mimeType) } } extension HTTPData: ResponseContentConvertible { public init?(content: ResponseContent?) { guard let content = content else { return nil } switch content { case .data(let value, let fileName, let mimeType): self.init(with: value, fileName: fileName ?? "", mimeType: mimeType) case .file(let url, let fileName, let mimeType): guard let data = try? Data(contentsOf: url, options: .mappedIfSafe) else { return nil } self.init(with: data, fileName: fileName ?? "", mimeType: mimeType) case .array, .dictionary, .string, .number: return nil } } }
33faa113b6b60f696dc0bda35e5f9547
26.717391
86
0.611765
false
false
false
false
amraboelela/swift
refs/heads/master
test/SourceKit/Indexing/index_operators.swift
apache-2.0
11
// RUN: %sourcekitd-test -req=index %s -- -Xfrontend -serialize-diagnostics-path -Xfrontend %t.dia %s | %sed_clean > %t.response // RUN: diff -u %s.response %t.response class ClassA { init(){} } func +(lhs: ClassA, rhs: ClassA) -> ClassA { return lhs } struct StructB { func method() { let a = ClassA() let b = a + a let c = StructB() let d = c - c } public static func -(lhs: StructB, rhs: StructB) -> StructB { return lhs } }
0ac3045646e9c03e8dbea943fd1728f8
20.565217
128
0.556452
false
false
false
false
GeekSpeak/GeekSpeak-Show-Timer
refs/heads/master
GeekSpeak Show Timer/BreakCount-3/Timer.swift
mit
2
import Foundation import CoreGraphics let oneMinute = TimeInterval(60) let timerUpdateInterval = TimeInterval(0.06) // MARK: - // MARK: Timer class final class Timer: NSObject { struct Constants { static let TimeChange = "kGPTTimeChange" static let CountingStatusChanged = "kGPTCountingStatusChanged" static let DurationChanged = "kGPTDurationChanged" static let UseDemoDurations = "useDemoDurations" static let UUIDId = "timerUUIDId" static let DemoId = "timerDemoId" static let StateId = "timerCountingStateId" static let PhaseId = "timerShowTimingPhaseId" static let CountingStartTimeId = "timerCountingStartTimeId" struct Durations { static let PreShowId = "timerShowTimingDurationPreShowId" static let Section1Id = "timerShowTimingDurationSection1Id" static let Section2Id = "timerShowTimingDurationSection2Id" static let Section3Id = "timerShowTimingDurationSection3Id" static let Break1Id = "timerShowTimingDurationBreak1Id" static let Break2Id = "timerShowTimingDurationBreak2Id" } struct ElapsedTime { static let PreShowId = "timerShowTimingElapsedPreShowId" static let Section1Id = "timerShowTimingElapsedSection1Id" static let Section2Id = "timerShowTimingElapsedSection2Id" static let Section3Id = "timerShowTimingElapsedSection3Id" static let Break1Id = "timerShowTimingElapsedBreak1Id" static let Break2Id = "timerShowTimingElapsedBreak2Id" static let PostShowId = "timerShowTimingElapsedPostShowId" } } // MARK: Properties var uuid = UUID() var countingStartTime: TimeInterval? var timing = ShowTiming() var demoTimings = false // MARK: Computed Properties var state: CountingState { get { return _state } set(newState) { changeCountingState(newState) } } var secondsElapsedAtPause: TimeInterval { get { return timing.elapsed } set(newElapsed) { timing.elapsed = newElapsed } } var duration: TimeInterval { get { return timing.duration } set(newDuration) { timing.duration = newDuration notifyTimerUpdated() notifyTimerDurationUpdated() } } var secondsElapsed: TimeInterval { var secondsElapsed: TimeInterval if let countingStartTime = countingStartTime { let now = Date.timeIntervalSinceReferenceDate secondsElapsed = now - countingStartTime + secondsElapsedAtPause } else { secondsElapsed = secondsElapsedAtPause } return secondsElapsed } var secondsRemaining: TimeInterval { let seconds = duration - secondsElapsed return max(seconds,0) } var totalShowTimeRemaining: TimeInterval { switch timing.phase { case .PreShow, .Break1, .Break2, .PostShow: return max(timing.totalShowTimeRemaining,0) case .Section1, .Section2, .Section3: return max(timing.totalShowTimeRemaining - secondsElapsed,0) } } var totalShowTimeElapsed: TimeInterval { switch timing.phase { case .PreShow, .Break1, .Break2, .PostShow: return max(timing.totalShowTimeElapsed,0) case .Section1, .Section2, .Section3: return max(timing.totalShowTimeElapsed + secondsElapsed,0) } } var percentageRemaining: CGFloat { return secondsToPercentage(secondsRemaining) } var percentageComplete: CGFloat { return 1.0 - percentageRemaining } func percentageComplete(_ phase: ShowPhase) -> CGFloat { var percentageComplete = Double(0.0) switch phase { case .PreShow, .Break1, .Break2: percentageComplete = Double(self.percentageComplete) case .Section1: // let a = timing.durations.section1 // let b = timing.timeElapsed.section1 // percentageComplete = 1 - ((a - b) / a) percentageComplete = (timing.durations.section1 - timing.timeElapsed.section1) / timing.durations.section1 case .Section2: percentageComplete = (timing.durations.section2 - timing.timeElapsed.section2) / timing.durations.section2 case .Section3: percentageComplete = (timing.durations.section3 - timing.timeElapsed.section3) / timing.durations.section3 case .PostShow: percentageComplete = 0.0 } return CGFloat(percentageComplete) } var percentageCompleteUnlimited: CGFloat { // The secondsRemaining computed property is limited so that // it can not be less than 0. This property is unlimited allowing // percentageComplete to be greater than 1.0 let percentageRemaining = secondsToPercentage(duration - secondsElapsed) let percentageComplete = 1.0 - percentageRemaining return percentageComplete } func percentageFromSeconds(_ seconds: TimeInterval) -> Double { let percent = seconds / duration return percent } func percentageFromSecondsToEnd(_ seconds: TimeInterval) -> Double { let percent = 1 - (seconds / duration) return percent } // MARK: Internal Properties var _state: CountingState = .Ready { didSet { onNextRunloopNotifyCountingStateUpdated() } } // MARK: - // MARK: Initialization override init() { super.init() } // MARK: - // MARK: Timer Actions func changeCountingState(_ state: CountingState) { switch state { case .Ready: reset() case .Counting, .CountingAfterComplete: start() case .Paused, .PausedAfterComplete: pause() } } func reset() { reset(usingDemoTiming: demoTimings) } func reset(usingDemoTiming demoTimings: Bool) { _state = .Ready countingStartTime = .none timing = ShowTiming() if demoTimings { timing.durations.useDemoDurations() self.demoTimings = true } else { self.demoTimings = false } notifyAll() } func start() { if percentageComplete < 1.0 { _state = .Counting } else { _state = .CountingAfterComplete } countingStartTime = Date.timeIntervalSinceReferenceDate incrementTimer() } func pause() { if percentageComplete < 1.0 { _state = .Paused } else { _state = .PausedAfterComplete } storeElapsedTimeAtPause() } func next() { storeElapsedTimeAtPause() countingStartTime = .none timing.incrementPhase() notifyTimerDurationUpdated() if percentageComplete > 1.0 || timing.phase == .PostShow { if _state == .Counting { _state = .CountingAfterComplete } if _state == .Paused { _state = .PausedAfterComplete } } switch _state { case .Ready: reset() case .Counting, .CountingAfterComplete: start() case .Paused, .PausedAfterComplete: notifyTimerUpdated() break } } func addTimeBySeconds(_ seconds: TimeInterval) { timing.duration += seconds switch state { case .Ready, .Paused: notifyTimerUpdated() case .Counting, .PausedAfterComplete, .CountingAfterComplete: break } } // MARK: - // MARK: Notify Observers fileprivate func notifyTimerUpdated() { NotificationCenter.default .post( name: Notification.Name(rawValue: Constants.TimeChange), object: self) } func notifyCountingStateUpdated() { NotificationCenter.default .post( name: Notification.Name(rawValue: Constants.CountingStatusChanged), object: self) } fileprivate func notifyTimerDurationUpdated() { NotificationCenter.default .post( name: Notification.Name(rawValue: Constants.DurationChanged), object: self) } func notifyAll() { notifyTimerUpdated() notifyCountingStateUpdated() notifyTimerDurationUpdated() } // MARK: - // MARK: Timer func incrementTimer() { switch state { case .Ready: break case .Paused, .PausedAfterComplete: storeElapsedTimeAtPause() case .Counting, .CountingAfterComplete: notifyTimerUpdated() checkTimingForCompletion() incrementTimerAgain() } } func checkTimingForCompletion() { if timing.durations.advancePhaseOnCompletion(timing.phase) { if percentageComplete >= 1.0 { next() } } } fileprivate func incrementTimerAgain() { Foundation.Timer.scheduledTimer( timeInterval: timerUpdateInterval, target: self, selector: #selector(Timer.incrementTimer), userInfo: nil, repeats: false) } fileprivate func storeElapsedTimeAtPause() { secondsElapsedAtPause = secondsElapsed countingStartTime = .none } // MARK: - // MARK: Helpers fileprivate func secondsToPercentage(_ secondsRemaining: TimeInterval) -> CGFloat { return CGFloat(secondsRemaining / duration) } // The timerChangedCountingStatus() is intended for acting on a change of state // only, and not intended as a callback to check property values of the // Timer class. (hense, only the TimerStatus emum is passed as the sole argument.) // If this callback IS used to check properties, they may not represent // the state of the timer correctly since the state is changed first and // drives rest of the class. Properties sensitive to this are: // secondsElapsedAtPause // countingStartTime // secondsElapsed (computed) // To mitigate this case, the state callback is delayed until the next // runloop using NSTimer with a delay of 0.0. fileprivate func onNextRunloopNotifyCountingStateUpdated() { Foundation.Timer.scheduledTimer( timeInterval: 0.0, target: self, selector: #selector(Timer.notifyCountingStateUpdated), userInfo: nil, repeats: false) } }
b0bb2a16bb54b1234ae8601536fdb138
26.84
98
0.633046
false
false
false
false
AliSoftware/SwiftGen
refs/heads/develop
Tests/SwiftGenTests/ConfigReadTests.swift
mit
1
// // SwiftGen UnitTests // Copyright © 2020 SwiftGen // MIT Licence // import PathKit @testable import SwiftGenCLI import TestUtils import XCTest final class ConfigReadTests: XCTestCase { private lazy var bundle = Bundle(for: type(of: self)) func testConfigWithParams() throws { let file = Fixtures.config(for: "config-with-params") do { let config = try Config(file: file) XCTAssertNil(config.inputDir) XCTAssertEqual(config.outputDir, "Common/Generated") XCTAssertEqual(config.commandNames, ["strings"]) let stringEntries = config.entries(for: "strings") XCTAssertEqual(stringEntries.count, 1) guard let entry = stringEntries.first else { return XCTFail("Expected a single strings entry") } XCTAssertEqual(entry.inputs, ["Sources1/Folder"]) XCTAssertEqual(entry.filter, ".*\\.strings") XCTAssertEqual(entry.outputs.count, 1) guard let output = entry.outputs.first else { return XCTFail("Expected a single strings entry output") } XCTAssertEqualDict( output.parameters, [ "foo": 5, "bar": ["bar1": 1, "bar2": 2, "bar3": [3, 4, ["bar3a": 50]]], "baz": ["Hey", "$HELLO world"] ] ) XCTAssertEqual(output.output, "strings.swift") XCTAssertEqual(output.template, .name("structured-swift5")) } catch let error { XCTFail("Error: \(error)") } } func testConfigWithENVS() throws { let paramsFile = Fixtures.config(for: "config-with-params") let envFile = Fixtures.config(for: "config-with-env-placeholder") do { let paramsConfig = try Config(file: paramsFile) let envConfig = try Config( file: envFile, env: ["SWIFTGEN_OUTPUT_DIR": "Common/Generated", "HELLO": "Hey"] ) XCTAssertEqual(paramsConfig.outputDir, envConfig.outputDir) guard let paramsList = paramsConfig.entries(for: "strings").first?.outputs.first?.parameters["baz"] as? [String], let envList = envConfig.entries(for: "strings").first?.outputs.first?.parameters["baz"] as? [String] else { return XCTFail("Could not find strings entry output") } XCTAssertEqual(paramsList, envList) } catch let error { XCTFail("Error: \(error)") } } func testConfigWithMultiEntries() throws { let file = Fixtures.config(for: "config-with-multi-entries") do { let config = try Config(file: file) XCTAssertEqual(config.inputDir, "Fixtures/") XCTAssertEqual(config.outputDir, "Generated/") XCTAssertEqual(config.commandNames, ["strings", "xcassets"]) // strings let stringsEntries = config.entries(for: "strings") XCTAssertEqual(stringsEntries.count, 1, "Expected a config entry for strings") XCTAssertEqual(stringsEntries[0].inputs, ["Strings/Localizable.strings"]) XCTAssertEqual(stringsEntries[0].outputs.count, 1) XCTAssertEqual(stringsEntries[0].outputs[0].output, "strings.swift") XCTAssertEqualDict(stringsEntries[0].outputs[0].parameters, ["enumName": "Loc"]) XCTAssertEqual(stringsEntries[0].outputs[0].template, .path("templates/custom-swift5")) // xcassets let xcassetsEntries = config.entries(for: "xcassets") XCTAssertEqual(xcassetsEntries.count, 3, "Expected a config entry for xcassets") // > xcassets[0] XCTAssertEqual(xcassetsEntries[0].inputs, ["XCAssets/Colors.xcassets"]) XCTAssertEqual(xcassetsEntries[0].outputs.count, 1) XCTAssertEqual(xcassetsEntries[0].outputs[0].output, "assets-colors.swift") XCTAssertEqualDict(xcassetsEntries[0].outputs[0].parameters, [:]) XCTAssertEqual(xcassetsEntries[0].outputs[0].template, .name("swift5")) // > xcassets[1] XCTAssertEqual(xcassetsEntries[1].inputs, ["XCAssets/Images.xcassets"]) XCTAssertEqual(xcassetsEntries[1].outputs.count, 1) XCTAssertEqual(xcassetsEntries[1].outputs[0].output, "assets-images.swift") XCTAssertEqualDict(xcassetsEntries[1].outputs[0].parameters, ["enumName": "Pics"]) XCTAssertEqual(xcassetsEntries[1].outputs[0].template, .name("custom-swift5")) // > xcassets[2] XCTAssertEqual(xcassetsEntries[2].inputs, ["XCAssets/Colors.xcassets", "XCAssets/Images.xcassets"]) XCTAssertEqual(xcassetsEntries[2].outputs.count, 1) XCTAssertEqual(xcassetsEntries[2].outputs[0].output, "assets-all.swift") XCTAssertEqualDict(xcassetsEntries[2].outputs[0].parameters, [:]) XCTAssertEqual(xcassetsEntries[2].outputs[0].template, .name("swift5")) } catch let error { XCTFail("Error: \(error)") } } func testConfigWithMultiOutputs() throws { let file = Fixtures.config(for: "config-with-multi-outputs") do { let config = try Config(file: file) XCTAssertEqual(config.inputDir, "Fixtures/") XCTAssertEqual(config.outputDir, "Generated/") XCTAssertEqual(config.commandNames, ["ib"]) // ib let ibEntries = config.entries(for: "ib") XCTAssertEqual(ibEntries.count, 1, "Expected a config entry for ib") XCTAssertEqual(ibEntries[0].inputs, ["IB-iOS"]) // > outputs[0] XCTAssertEqual(ibEntries[0].outputs.count, 2) XCTAssertEqual(ibEntries[0].outputs[0].template, .name("scenes-swift5")) XCTAssertEqual(ibEntries[0].outputs[0].output, "ib-scenes.swift") XCTAssertEqualDict(ibEntries[0].outputs[0].parameters, ["enumName": "Scenes"]) // > outputs[1] XCTAssertEqual(ibEntries[0].outputs[1].template, .name("segues-swift5")) XCTAssertEqual(ibEntries[0].outputs[1].output, "ib-segues.swift") XCTAssertEqualDict(ibEntries[0].outputs[1].parameters, [:]) } catch let error { XCTFail("Error: \(error)") } } // MARK: - Invalid configs func testInvalidConfigThrows() { let badConfigs = [ "config-missing-paths": "Missing entry for key strings.inputs.", "config-missing-template": """ You must specify a template by name (templateName) or path (templatePath). To list all the available named templates, use 'swiftgen template list'. """, "config-both-templates": """ You need to choose EITHER a named template OR a template path. \ Found name 'template' and path 'template.swift' """, "config-missing-output": "Missing entry for key strings.outputs.output.", "config-invalid-structure": """ Wrong type for key strings.inputs: expected String or Array of String, got Array<Any>. """, "config-invalid-template": "Wrong type for key strings.outputs.templateName: expected String, got Array<Any>.", "config-invalid-output": "Wrong type for key strings.outputs.output: expected String, got Array<Any>." ] for (configFile, expectedError) in badConfigs { do { let path = Fixtures.config(for: configFile) _ = try Config(file: path) XCTFail( """ Trying to parse config file \(configFile) should have thrown \ error \(expectedError) but didn't throw at all """ ) } catch let error { XCTAssertEqual( String(describing: error), expectedError, """ Trying to parse config file \(configFile) should have thrown \ error \(expectedError) but threw \(error) instead. """ ) } } } // MARK: - Deprecations func testDeprecatedOutput() throws { let file = Fixtures.config(for: "config-deprecated-output") do { let config = try Config(file: file) guard let entry = config.entries(for: "strings").first else { return XCTFail("Strings entry not found") } XCTAssertEqual(entry.outputs.count, 1) guard let output = entry.outputs.first else { return XCTFail("Expected a single strings entry output") } XCTAssertEqualDict(output.parameters, ["foo": "baz"]) XCTAssertEqual(output.output, "my-strings.swift") XCTAssertEqual(output.template, .name("structured-swift4")) } catch let error { XCTFail("Error: \(error)") } } func testDeprecatedPaths() throws { let file = Fixtures.config(for: "config-deprecated-paths") do { let config = try Config(file: file) guard let entry = config.entries(for: "strings").first else { return XCTFail("Strings entry not found") } XCTAssertEqual(entry.inputs, ["Sources2/Folder"]) } catch let error { XCTFail("Error: \(error)") } } func testDeprecatedUseNewerProperties() throws { let file = Fixtures.config(for: "config-deprecated-mixed-with-new") do { let config = try Config(file: file) XCTAssertNil(config.inputDir) XCTAssertEqual(config.outputDir, "Common/Generated") XCTAssertEqual(config.commandNames, ["strings"]) let stringEntries = config.entries(for: "strings") XCTAssertEqual(stringEntries.count, 2, "Expected 2 config entry for strings") // > strings[0] XCTAssertEqual(stringEntries[0].inputs, ["new-inputs1"]) XCTAssertEqual(stringEntries[0].outputs.count, 1) XCTAssertEqualDict(stringEntries[0].outputs[0].parameters, ["foo": "new-param1"]) XCTAssertEqual(stringEntries[0].outputs[0].output, "new-output1") XCTAssertEqual(stringEntries[0].outputs[0].template, .name("new-templateName1")) // > strings[1] XCTAssertEqual(stringEntries[1].inputs, ["new-inputs2"]) XCTAssertEqual(stringEntries[1].outputs.count, 1) XCTAssertEqualDict(stringEntries[1].outputs[0].parameters, ["foo": "new-param2"]) XCTAssertEqual(stringEntries[1].outputs[0].output, "new-output2") XCTAssertEqual(stringEntries[1].outputs[0].template, .path("new-templatePath2")) } catch let error { XCTFail("Error: \(error)") } } }
2a384116d7489b42d0c3fccd6509d20e
36.812261
119
0.657817
false
true
false
false
BarTabs/bartabs
refs/heads/master
ios-application/Bar Tabs/OpenOrdersViewController.swift
gpl-3.0
1
// // openOrdersViewController.swift // Bar Tabs // // Created by Victor Lora on 4/6/17. // Copyright © 2017 muhlenberg. All rights reserved. /* This view controller enables employees to view all of the orders that need to be completed. The employee can see which user placed the order and complete the order. A notification will be sent to the user once his/her order has been completed. */ import UIKit import Alamofire import SwiftyJSON class OpenOrdersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var orders : JSON? var selectedOrder: JSON? var timer: Timer? @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Open Orders" self.automaticallyAdjustsScrollViewInsets = false tableView.delegate = self tableView.dataSource = self } override func viewDidDisappear(_ animated: Bool) { timer?.invalidate() } override func viewWillAppear(_ animated: Bool) { fetchData(showActivityIndicator: true) timer = Timer.scheduledTimer(timeInterval: 5, target:self, selector: #selector(self.reloadData), userInfo: nil, repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.orders?.count) ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if (self.orders != nil) { let jsonVar : JSON = self.orders! let orderID = jsonVar[indexPath.row]["objectID"].int64 let orderedDate = jsonVar[indexPath.row]["orderedDateDisplay"].stringValue cell.textLabel?.text = "Order #" + orderID!.description; cell.detailTextLabel?.text = orderedDate } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let jsonVar : JSON = self.orders! selectedOrder = jsonVar[indexPath.row] if let orderID = selectedOrder?["objectID"].int64 { let service = "order/getorderitems" let parameters: Parameters = [ "orderID": orderID ] let dataService = DataService(view: self) dataService.fetchData(service: service, parameters: parameters, completion: {(response: JSON) -> Void in self.performSegue(withIdentifier: "orderSegue", sender: (response.array)) }) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "orderSegue" { let destSeg = segue.destination as! OrderViewController destSeg.items = (sender as? [JSON])! destSeg.fromOpenOrder = true destSeg.orderID = selectedOrder?["objectID"].int64 if selectedOrder?["total"] != JSON.null { if let total = selectedOrder?["total"].doubleValue { destSeg.total = String(format:"$%.02f", total) } } } } func fetchData(showActivityIndicator: Bool) { let service = "order/getbarorders" let parameters: Parameters = [ "barID": 4, "openOnly": true ] let dataService = DataService(view: self) dataService.fetchData(service: service, parameters: parameters, showActivityIndicator:showActivityIndicator, completion: {(response: JSON) -> Void in self.orders = response self.tableView.reloadData() }) } func reloadData() { fetchData(showActivityIndicator: false) } }
005fae1e1a7e48353752a75590c097a4
32.641667
157
0.613327
false
false
false
false
HongliYu/firefox-ios
refs/heads/master
Storage/SQL/SQLiteReadingList.swift
mpl-2.0
4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger import Deferred private let log = Logger.syncLogger class ReadingListStorageError: MaybeErrorType { var message: String init(_ message: String) { self.message = message } var description: String { return message } } open class SQLiteReadingList { let db: BrowserDB let allColumns = ["client_id", "client_last_modified", "id", "last_modified", "url", "title", "added_by", "archived", "favorite", "unread"].joined(separator: ",") required public init(db: BrowserDB) { self.db = db } } extension SQLiteReadingList: ReadingList { public func getAvailableRecords() -> Deferred<Maybe<[ReadingListItem]>> { let sql = "SELECT \(allColumns) FROM items ORDER BY client_last_modified DESC" return db.runQuery(sql, args: nil, factory: SQLiteReadingList.ReadingListItemFactory) >>== { cursor in return deferMaybe(cursor.asArray()) } } public func deleteRecord(_ record: ReadingListItem) -> Success { let sql = "DELETE FROM items WHERE client_id = ?" let args: Args = [record.id] return db.run(sql, withArgs: args) } public func deleteAllRecords() -> Success { let sql = "DELETE FROM items" return db.run(sql) } public func createRecordWithURL(_ url: String, title: String, addedBy: String) -> Deferred<Maybe<ReadingListItem>> { return db.transaction { connection -> ReadingListItem in let insertSQL = "INSERT OR REPLACE INTO items (client_last_modified, url, title, added_by) VALUES (?, ?, ?, ?)" let insertArgs: Args = [ReadingListNow(), url, title, addedBy] let lastInsertedRowID = connection.lastInsertedRowID try connection.executeChange(insertSQL, withArgs: insertArgs) if connection.lastInsertedRowID == lastInsertedRowID { throw ReadingListStorageError("Unable to insert ReadingListItem") } let querySQL = "SELECT \(self.allColumns) FROM items WHERE client_id = ? LIMIT 1" let queryArgs: Args = [connection.lastInsertedRowID] let cursor = connection.executeQuery(querySQL, factory: SQLiteReadingList.ReadingListItemFactory, withArgs: queryArgs) let items = cursor.asArray() if let item = items.first { return item } else { throw ReadingListStorageError("Unable to get inserted ReadingListItem") } } } public func getRecordWithURL(_ url: String) -> Deferred<Maybe<ReadingListItem>> { let sql = "SELECT \(allColumns) FROM items WHERE url = ? LIMIT 1" let args: Args = [url] return db.runQuery(sql, args: args, factory: SQLiteReadingList.ReadingListItemFactory) >>== { cursor in let items = cursor.asArray() if let item = items.first { return deferMaybe(item) } else { return deferMaybe(ReadingListStorageError("Can't create RLCR from row")) } } } public func updateRecord(_ record: ReadingListItem, unread: Bool) -> Deferred<Maybe<ReadingListItem>> { return db.transaction { connection -> ReadingListItem in let updateSQL = "UPDATE items SET unread = ? WHERE client_id = ?" let updateArgs: Args = [unread, record.id] try connection.executeChange(updateSQL, withArgs: updateArgs) let querySQL = "SELECT \(self.allColumns) FROM items WHERE client_id = ? LIMIT 1" let queryArgs: Args = [record.id] let cursor = connection.executeQuery(querySQL, factory: SQLiteReadingList.ReadingListItemFactory, withArgs: queryArgs) let items = cursor.asArray() if let item = items.first { return item } else { throw ReadingListStorageError("Unable to get updated ReadingListItem") } } } fileprivate class func ReadingListItemFactory(_ row: SDRow) -> ReadingListItem { let id = row["client_id"] as! Int let lastModified = row.getTimestamp("client_last_modified")! let url = row["url"] as! String let title = row["title"] as! String let addedBy = row["added_by"] as! String let archived = row.getBoolean("archived") let unread = row.getBoolean("unread") let favorite = row.getBoolean("favorite") return ReadingListItem(id: id, lastModified: lastModified, url: url, title: title, addedBy: addedBy, unread: unread, archived: archived, favorite: favorite) } }
7beeaaa3dc525c813a7c0ebcf361c812
38.909836
166
0.63319
false
false
false
false
AnRanScheme/MagiRefresh
refs/heads/master
Example/MagiRefresh/MagiRefresh/Extension/UIView+MagiRefresh.swift
mit
3
// // UIView+Position.swift // magiLoadingPlaceHolder // // Created by 安然 on 2018/7/30. // Copyright © 2018年 anran. All rights reserved. // import UIKit import Foundation extension UIView { //frame.origin.x var magi_left: CGFloat { get { return self.frame.origin.x } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } //frame.origin.y var magi_top: CGFloat { get { return self.frame.origin.y } set { var frame = self.frame frame.origin.y = newValue self.frame = frame } } //frame.origin.x + frame.size.width var magi_right: CGFloat { get { return self.frame.origin.x + self.frame.size.width } set { var frame = self.frame frame.origin.x = newValue - frame.size.width self.frame = frame } } //frame.origin.y + frame.size.height var magi_bottom: CGFloat { get { return self.frame.origin.y + self.frame.size.height } set { var frame = self.frame frame.origin.y = newValue - frame.origin.y self.frame = frame } } //frame.size.width var magi_width: CGFloat { get { return self.frame.size.width } set { var frame = self.frame frame.size.width = newValue self.frame = frame } } //frame.size.height var magi_height: CGFloat { get { return self.frame.size.height } set { var frame = self.frame frame.size.height = newValue self.frame = frame } } //center.x var magi_centerX: CGFloat { get { return self.center.x } set { self.center = CGPoint(x: newValue, y: self.center.y) } } //center.y var magi_centerY: CGFloat { get { return self.center.y } set { self.center = CGPoint(x: self.center.x, y: newValue) } } //frame.origin var magi_origin: CGPoint { get { return self.frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } //frame.size var magi_size: CGSize { get { return self.frame.size } set { var frame = self.frame frame.size = newValue self.frame = frame } } //maxX var magi_maxX: CGFloat { get { return self.frame.origin.x + self.frame.size.width } } //maxY var magi_maxY: CGFloat { get { return self.frame.origin.y + self.frame.size.height } } public class func setAnimate(animations: @escaping (()->Void), completion: ((Bool)->Void)? = nil) { UIView.animate(withDuration: 0.15, delay: 0, options: .curveLinear, animations: animations, completion: completion) } }
6a516fdd88aa006063012e8ebd0e8c9d
21.296774
66
0.457465
false
false
false
false
darrinhenein/firefox-ios
refs/heads/master
Storage/Storage/JoinedFaviconsHistoryTable.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation private let FaviconVisits = "faviconSiteMapping" // This isn't a real table. Its an abstraction around the history and visits table // to simpify queries that should join both tables. It also handles making sure that // inserts/updates/delete update both tables appropriately. i.e. // 1.) Deleteing a history entry here will also remove all visits to it // 2.) Adding a visit here will ensure that a site exists for the visit // 3.) Updates currently only update site information. class JoinedFaviconsHistoryTable<T>: GenericTable<(site: Site?, icon: Favicon?)> { private let favicons: FaviconsTable<Favicon> private let history: HistoryTable<Site> init(files: FileAccessor) { self.favicons = FaviconsTable<Favicon>(files: files) self.history = HistoryTable<Site>() } override var name: String { return FaviconVisits } override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteId INTEGER NOT NULL, " + "faviconId INTEGER NOT NULL" } override func getInsertAndArgs(inout item: Type) -> (String, [AnyObject?])? { var args = [AnyObject?]() args.append(item.site!.id) args.append(item.icon!.id) return ("INSERT INTO \(name) (siteId, faviconId) VALUES (?,?)", args) } override func getUpdateAndArgs(inout item: Type) -> (String, [AnyObject?])? { // We don't support updates here... return nil } override func getDeleteAndArgs(inout item: Type?) -> (String, [AnyObject?])? { var args = [AnyObject?]() var sql = "DELETE FROM \(FaviconVisits)" if let item = item { sql += " WHERE" if let site = item.site { args.append(site.id!) sql += " siteId = ?" } if let icon = item.icon { args.append(icon.id!) sql += " faviconId = ?" } } println("Delete \(sql) \(args)") return (sql, args) } override func create(db: SQLiteDBConnection, version: Int) -> Bool { history.create(db, version: version) favicons.create(db, version: version) return super.create(db, version: version) } override func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool { if history.updateTable(db, from: from, to: to) && favicons.updateTable(db, from: from, to: to) { return super.updateTable(db, from: from, to: to) } return false } override func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { if let (site, favicon) = item { if let site = site { history.insertOrUpdate(db, obj: site) } else { println("Must have a site to insert in \(name)") return -1 } if let icon = favicon { favicons.insertOrUpdate(db, obj: icon) } else { println("Must have an icon to insert in \(name)") return -1 } let args: [AnyObject?] = [item?.icon?.id, item?.site?.id] let c = db.executeQuery("SELECT * FROM \(FaviconVisits) WHERE faviconId = ? AND siteId = ?", factory: { (row) -> Type in return (nil, nil) }, withArgs: args) if c.count > 0 { return -1 } return super.insert(db, item: item, err: &err) } return -1 } override func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { if let (site, favicon) = item { history.update(db, item: site, err: &err) favicons.update(db, item: favicon, err: &err) return super.update(db, item: item, err: &err) } return -1 } func factory(result: SDRow) -> (Site, Favicon) { let site = Site(url: result["siteUrl"] as String, title: result["title"] as String) site.guid = result["guid"] as? String site.id = result["historyId"] as? Int let favicon = Favicon(url: result["iconUrl"] as String, date: NSDate(timeIntervalSince1970: result["date"] as Double), type: IconType(rawValue: result["iconType"] as Int)!) favicon.id = result["iconId"] as? Int return (site, favicon) } override func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor { var args = [AnyObject?]() var sql = "SELECT \(history.name).id as historyId, \(history.name).url as siteUrl, title, guid, " + "\(favicons.name).id as iconId, \(favicons.name).url as iconUrl, date, \(favicons.name).type as iconType FROM \(history.name) " + "INNER JOIN \(FaviconVisits) ON \(history.name).id = \(FaviconVisits).siteId " + "INNER JOIN \(favicons.name) ON \(favicons.name).id = \(FaviconVisits).faviconId"; if let filter: AnyObject = options?.filter { sql += " WHERE siteUrl LIKE ?" args.append("%\(filter)%") } println("\(sql) \(args)") return db.executeQuery(sql, factory: factory, withArgs: args) } }
f15feb39fbc28344b9778a24b7aa978e
37.560284
147
0.579364
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_2_fixed/0195-sr10438.swift
apache-2.0
20
// RUN: %target-swift-frontend -typecheck %s protocol AuthenticationFlowStateMachine { associatedtype StartState: AuthenticationFlowStateMachineStartState where StartState.StateMachine == Self associatedtype NonFinalState: AuthenticationFlowStateMachineNonFinalState where NonFinalState.StateMachine == Self associatedtype FlowError: AuthenticationFlowStateMachineFlowError where FlowError.StateMachine == Self } protocol AuthenticationFlowStateMachineFlowError: Error { associatedtype StateMachine: AuthenticationFlowStateMachine where StateMachine.FlowError == Self } protocol AuthenticationFlowStateMachineStartState { associatedtype StateMachine: AuthenticationFlowStateMachine where StateMachine.StartState == Self var nonFinalState: StateMachine.NonFinalState { get } } protocol AuthenticationFlowStateMachineNonFinalState { associatedtype StateMachine: AuthenticationFlowStateMachine where StateMachine.NonFinalState == Self }
ba0ad61d76c1e0bb58993d75dfb48fa5
47.3
118
0.847826
false
false
false
false
bull-xu-stride/MaterialDesignIcons.Swift
refs/heads/master
MaterialDesignIconsSwift/FontLoader.swift
mit
1
// // FontLoader.swift // MaterialDesignIconsSwift // // Created by Bull Xu on 8/09/2016. // Copyright © 2016 Stride Solutions. All rights reserved. // import Foundation import CoreText /// FontLoad class to load the font file. /// Code copied from https://github.com/thii/FontAwesome.swift. // Thanks to Thi, the author of FontAwesome.swift. internal class FontLoader { internal class func loadFont(_ name: String, withExtension ext: String = "ttf") { let bundle = Bundle(for: FontLoader.self) let identifier = bundle.bundleIdentifier let fontURL: URL? if identifier?.hasPrefix("org.cocoapods") == true { // If this framework is added using CocoaPods, resources is placed under a subdirectory fontURL = bundle.url( forResource: name, withExtension: ext, subdirectory: "MaterialDesignIconsSwift.bundle") } else { fontURL = bundle.url(forResource: name, withExtension: ext) } guard let url = fontURL, let data = try? Data(contentsOf: url), let provider = CGDataProvider(data: data as CFData), let font = CGFont(provider) else { return } var error: Unmanaged<CFError>? if CTFontManagerRegisterGraphicsFont(font, &error) { return } if let error = error, let nsError = error.takeUnretainedValue() as AnyObject as? NSError { let errorDescription: CFString = CFErrorCopyDescription(error.takeUnretainedValue()) NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } } }
84dfaae09db49f0b96e3d9de59f6c3f7
31.102041
92
0.717101
false
false
false
false
skyfe79/RxPlayground
refs/heads/master
RxAlamorefire/Pods/RxDataSources/Sources/DataSources/Changeset.swift
mit
2
// // Changeset.swift // RxDataSources // // Created by Krunoslav Zaher on 5/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import CoreData #if !RX_NO_MODULE import RxSwift import RxCocoa #endif public struct Changeset<S: SectionModelType> { public typealias I = S.Item public let reloadData: Bool public let finalSections: [S] public let insertedSections: [Int] public let deletedSections: [Int] public let movedSections: [(from: Int, to: Int)] public let updatedSections: [Int] public let insertedItems: [ItemPath] public let deletedItems: [ItemPath] public let movedItems: [(from: ItemPath, to: ItemPath)] public let updatedItems: [ItemPath] init(reloadData: Bool = false, finalSections: [S] = [], insertedSections: [Int] = [], deletedSections: [Int] = [], movedSections: [(from: Int, to: Int)] = [], updatedSections: [Int] = [], insertedItems: [ItemPath] = [], deletedItems: [ItemPath] = [], movedItems: [(from: ItemPath, to: ItemPath)] = [], updatedItems: [ItemPath] = [] ) { self.reloadData = reloadData self.finalSections = finalSections self.insertedSections = insertedSections self.deletedSections = deletedSections self.movedSections = movedSections self.updatedSections = updatedSections self.insertedItems = insertedItems self.deletedItems = deletedItems self.movedItems = movedItems self.updatedItems = updatedItems } public static func initialValue(sections: [S]) -> Changeset<S> { return Changeset<S>( insertedSections: Array(0 ..< sections.count) as [Int], finalSections: sections, reloadData: true ) } } extension ItemPath : CustomDebugStringConvertible { public var debugDescription : String { get { return "(\(sectionIndex), \(itemIndex))" } } } extension Changeset : CustomDebugStringConvertible { public var debugDescription : String { get { let serializedSections = "[\n" + finalSections.map { "\($0)" }.joinWithSeparator(",\n") + "\n]\n" return " >> Final sections" + " \n\(serializedSections)" + (insertedSections.count > 0 || deletedSections.count > 0 || movedSections.count > 0 || updatedSections.count > 0 ? "\nSections:" : "") + (insertedSections.count > 0 ? "\ninsertedSections:\n\t\(insertedSections)" : "") + (deletedSections.count > 0 ? "\ndeletedSections:\n\t\(deletedSections)" : "") + (movedSections.count > 0 ? "\nmovedSections:\n\t\(movedSections)" : "") + (updatedSections.count > 0 ? "\nupdatesSections:\n\t\(updatedSections)" : "") + (insertedItems.count > 0 || deletedItems.count > 0 || movedItems.count > 0 || updatedItems.count > 0 ? "\nItems:" : "") + (insertedItems.count > 0 ? "\ninsertedItems:\n\t\(insertedItems)" : "") + (deletedItems.count > 0 ? "\ndeletedItems:\n\t\(deletedItems)" : "") + (movedItems.count > 0 ? "\nmovedItems:\n\t\(movedItems)" : "") + (updatedItems.count > 0 ? "\nupdatedItems:\n\t\(updatedItems)" : "") } } }
617c503cacc196f1529c87fa1f111e87
33.061224
148
0.602756
false
false
false
false
rsahara/dopamine
refs/heads/master
Dopamine/Core/FloatBuffer.swift
mit
1
// // FloatBuffer.swift // Dopamine // // Created by Runo Sahara on 2017/05/02. // Copyright © 2017 Runo Sahara. All rights reserved. // import Foundation public class FloatBuffer { #if DEBUG public var DEBUG_BUFFERINITIALIZATION = false // Make a buffer initialized with NaN #endif public typealias Pointer = UnsafeMutablePointer<Float> public init(_ rows: Int, _ columns: Int) { _rows = rows _columns = columns _capacity = rows * columns _allocationSize = _capacity _buffer = Pointer.allocate(capacity: _allocationSize) #if DEBUG if DEBUG_BUFFERINITIALIZATION { for index in 0 ..< _capacity { _buffer[index] = Float.nan } } #endif } public convenience init(like src: FloatBuffer) { self.init(src._rows, src._columns) } public init(referenceOf pointer: Pointer, rows: Int, columns: Int) { _rows = rows; _columns = columns _capacity = rows * columns _allocationSize = 0 _buffer = pointer } public convenience init(referenceOf src: FloatBuffer, startRow: Int, startColumn: Int, rows: Int, columns: Int) { assert(startRow < src._rows) assert(startColumn < src._columns) assert(startRow * src._columns + startColumn + rows * columns <= src._capacity) self.init(referenceOf: src._buffer + (startRow * src._columns + startColumn), rows: rows, columns: columns) } public convenience init(referenceOf src: FloatBuffer, rowIndex: Int) { self.init(referenceOf: src, startRow: rowIndex, startColumn: 0, rows: 1, columns: src._columns) } deinit { if _allocationSize != 0 { _buffer.deallocate(capacity: _allocationSize) } } // MARK: - Main features public func fillZero() { _FloatBuffer_FillZero(_buffer, Int32(_capacity)) } public func fillRandom() { _FloatBuffer_FillRandomGaussian(_buffer, Int32(capacity)) } public func print() { var valuesStr = "" for vectIndex in stride(from: 0, to: _capacity, by: _columns) { for valIndex in vectIndex ..< vectIndex + _columns { valuesStr += "\(_buffer[valIndex])," } valuesStr += "|" } Swift.print("Buffer[\(_rows)x\(_columns)] \(valuesStr)") } public func copy(from src: FloatBuffer) { reshape(like: src) memcpy(_buffer, src._buffer, _capacity * 4) } public func subcopy(from src: FloatBuffer, startRow: Int, startColumn: Int) { assert(startRow + _rows <= src._rows) assert(startColumn + _columns <= src._columns) // TODO: transcode to C++ for y in 0 ..< _rows { memcpy(_buffer + (y * _columns), src._buffer + ((y + startRow) * src._columns + startColumn), _columns * 4) } } // Concatenate left and right, row-wise public func copyConcatRows(left: FloatBuffer, right: FloatBuffer) { assert(left._rows == right._rows) // TODO: transcode to C++ let resColumns = left._columns + right._columns resetLazy(left._rows, resColumns) // TODO: reshape assert(_capacity == left._capacity + right._capacity) for y in 0 ..< left._rows { let headRes = _buffer + (y * resColumns) let headLeft = left._buffer + (y * left._columns) let headRight = right._buffer + (y * right._columns) memcpy(headRes, headLeft, left._columns * 4) memcpy(headRes + left._columns, headRight, right._columns * 4) } } public func reshape(_ rows: Int, _ columns: Int) { let capacity = rows * columns assert(capacity <= _allocationSize) _rows = rows _columns = columns _capacity = capacity #if DEBUG if DEBUG_BUFFERINITIALIZATION { for index in 0 ..< _capacity { _buffer[index] = Float.nan } } #endif } public func reshape(like src: FloatBuffer) { reshape(src._rows, src._columns) } // TODO: Remove, use reshape and precalculate required memory size private func resetLazy(_ rows: Int, _ columns: Int) { let capacity = rows * columns if (capacity > _allocationSize) { Swift.print("FloatBuffer: resetLazy: realloc") if _allocationSize != 0 { _buffer.deallocate(capacity: _allocationSize) } _allocationSize = capacity _buffer = Pointer.allocate(capacity: _allocationSize) } _rows = rows _columns = columns _capacity = capacity #if DEBUG if DEBUG_BUFFERINITIALIZATION { for index in 0 ..< _capacity { _buffer[index] = Float.nan } } #endif } // MARK: - Properties public var capacity: Int { return _capacity } public var contents: Pointer { return _buffer } public var rows: Int { return _rows } public var columns: Int { return _columns } // MARK: - Hidden internal static let ALIGNMENT = 8 internal var _buffer: Pointer internal var _rows: Int internal var _columns: Int // internal var _stride: Int internal var _capacity: Int internal var _allocationSize: Int } // MARK: - Save/Load extension FloatBuffer { public convenience init(data: Data) { let headerBuffer = UnsafeMutableRawPointer.allocate(bytes: FloatBuffer.HEADERSIZE, alignedTo: FloatBuffer.ALIGNMENT) defer { headerBuffer.deallocate(bytes: FloatBuffer.HEADERSIZE, alignedTo: FloatBuffer.ALIGNMENT) } data.copyBytes(to: headerBuffer.assumingMemoryBound(to: UInt8.self), count: FloatBuffer.HEADERSIZE) let rows = headerBuffer.load(as: Int32.self) let columns = (headerBuffer + 4).load(as: Int32.self) self.init(Int(rows), Int(columns)) data.advanced(by: FloatBuffer.HEADERSIZE).copyBytes(to: UnsafeMutableRawPointer(_buffer).assumingMemoryBound(to: UInt8.self), count: _capacity * 4) } public convenience init(contentsOf url: URL) throws { self.init(data: try Data(contentsOf: url)) } public func write(to path: URL) throws { var data = Data(capacity: writeSize()) write(to: &data) try data.write(to: path, options: Data.WritingOptions.atomic) } public func write(to data: inout Data) { let headerBuffer = UnsafeMutableRawPointer.allocate(bytes: FloatBuffer.HEADERSIZE, alignedTo: FloatBuffer.ALIGNMENT) defer { headerBuffer.deallocate(bytes: FloatBuffer.HEADERSIZE, alignedTo: FloatBuffer.ALIGNMENT) } headerBuffer.storeBytes(of: Int32(_rows), as: Int32.self) (headerBuffer + 4).storeBytes(of: Int32(_columns), as: Int32.self) data.append(UnsafeBufferPointer<UInt8>(start: headerBuffer.assumingMemoryBound(to: UInt8.self), count: FloatBuffer.HEADERSIZE)) data.append(UnsafeBufferPointer<Float>(start: _buffer, count: _capacity)) } public func writeSize() -> Int { return FloatBuffer.HEADERSIZE + _capacity } internal static let HEADERSIZE = 64 } extension Data { init(floatBuffer: FloatBuffer) { self.init(capacity: floatBuffer.writeSize()) floatBuffer.write(to: &self) } }
6ec44f4ea554288f5087b34f76526c16
23.692884
149
0.684969
false
false
false
false
ephread/Instructions
refs/heads/main
Examples/Example/Snapshot Tests/DefaultExampleSnapshotTests.swift
mit
1
// Copyright (c) 2018-present Frédéric Maquin <[email protected]> and contributors. // Licensed under the terms of the MIT License. #if targetEnvironment(macCatalyst) #else import DeviceKit import iOSSnapshotTestCase import Darwin class DefaultExampleSnapshotTests: FBSnapshotTestCase { var snapshotIndex: Int = 0 override func setUp() { super.setUp() snapshotIndex = 0 fileNameOptions = [.screenScale] recordMode = ProcessInfo.processInfo.environment["RECORD_MODE"] != nil XCUIApplication().launchWithoutStatusBar() XCUIDevice.shared.orientation = .portrait } override func tearDown() { super.tearDown() XCUIDevice.shared.orientation = .portrait snapshotIndex = 0 } func testFlowInIndependentWindow() { performSnapshotTest(in: .independentWindow) } func testRotationInIndependentWindow() { performSnapshotTest(in: .independentWindow, rotating: true) } func testFlowInWindow() { performSnapshotTest(in: .sameWindow) } func testRotationInWindow() { performSnapshotTest(in: .sameWindow, rotating: true) } func testFlowInController() { performSnapshotTest(in: .controller) } func testRotationInController() { performSnapshotTest(in: .controller, rotating: true) } func performSnapshotTest( in context: Context, rotating: Bool = false ) { let app = XCUIApplication() switch context { case .independentWindow: let cell = app.tables.staticTexts["Independent Window"] cell.tap() case .sameWindow: let cell = app.tables.staticTexts["Controller Window"] cell.tap() case .controller: let cell = app.tables.staticTexts["Controller"] cell.tap() } let body = app.otherElements["AccessibilityIdentifiers.coachMarkBody"] for _ in 0..<5 { if body.waitForExistence(timeout: 5) { snapshot(app, presentationContext: context) body.tap() if rotating { let currentOrientation = XCUIDevice.shared.orientation if currentOrientation == .portrait { XCUIDevice.shared.orientation = .landscapeLeft } else if currentOrientation == .landscapeLeft { XCUIDevice.shared.orientation = .portrait } } } } } func snapshot(_ app: XCUIApplication, presentationContext: Context) { // When animations are involved, even when disabled, snapshotting through // UI Testing is remarkably brittle -> sleeping for additional stability // when snapshotting. // // TODO: Figure out a way to use Point-Free's library while mimicking // proper behaviour. Thread.sleep(forTimeInterval: 0.1) let orientation = XCUIDevice.shared.orientation let image = app.screenshot().image let imageView = UIImageView(image: image.cropped(using: orientation)) let identifier = """ \(presentationContext.name)_\(snapshotIndex)_\ \(orientation.name)_\(Device.current.snapshotDescription) """ FBSnapshotVerifyView( imageView, identifier: identifier, perPixelTolerance: 0.1, overallTolerance: 0.002 ) snapshotIndex += 1 } } enum Context: String { case independentWindow, sameWindow, controller var name: String { rawValue } } extension UIDeviceOrientation { var name: String { switch self { case .unknown: return "unknown" case .portrait: return "portrait" case .portraitUpsideDown: return "portraitUpsideDown" case .landscapeLeft: return "landscapeLeft" case .landscapeRight: return "landscapeRight" case .faceUp: return "faceUp" case .faceDown: return "faceDown" @unknown default: return "unknown" } } } #endif
a83d233a985e79fc5137dac199aa84d4
28.652482
82
0.607749
false
true
false
false
HongliYu/firefox-ios
refs/heads/master
Shared/NotificationConstants.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extension Notification.Name { public static let DataLoginDidChange = Notification.Name("DataLoginDidChange") // add a property to allow the observation of firefox accounts public static let FirefoxAccountChanged = Notification.Name("FirefoxAccountChanged") public static let FirefoxAccountProfileChanged = Notification.Name("FirefoxAccountProfileChanged") public static let FirefoxAccountDeviceRegistrationUpdated = Notification.Name("FirefoxAccountDeviceRegistrationUpdated") public static let PrivateDataClearedHistory = Notification.Name("PrivateDataClearedHistory") public static let PrivateDataClearedDownloadedFiles = Notification.Name("PrivateDataClearedDownloadedFiles") // Fired when the user finishes navigating to a page and the location has changed public static let OnLocationChange = Notification.Name("OnLocationChange") // MARK: Notification UserInfo Keys public static let UserInfoKeyHasSyncableAccount = Notification.Name("UserInfoKeyHasSyncableAccount") // Fired when the FxA account has been verified. This should only be fired by the FxALoginStateMachine. public static let FirefoxAccountVerified = Notification.Name("FirefoxAccountVerified") // Fired when the login synchronizer has finished applying remote changes public static let DataRemoteLoginChangesWereApplied = Notification.Name("DataRemoteLoginChangesWereApplied") // Fired when a the page metadata extraction script has completed and is being passed back to the native client public static let OnPageMetadataFetched = Notification.Name("OnPageMetadataFetched") public static let ProfileDidStartSyncing = Notification.Name("ProfileDidStartSyncing") public static let ProfileDidFinishSyncing = Notification.Name("ProfileDidFinishSyncing") public static let DatabaseWasRecreated = Notification.Name("DatabaseWasRecreated") public static let DatabaseWasClosed = Notification.Name("DatabaseWasClosed") public static let DatabaseWasReopened = Notification.Name("DatabaseWasReopened") public static let PasscodeDidChange = Notification.Name("PasscodeDidChange") public static let PasscodeDidCreate = Notification.Name("PasscodeDidCreate") public static let PasscodeDidRemove = Notification.Name("PasscodeDidRemove") public static let DynamicFontChanged = Notification.Name("DynamicFontChanged") public static let UserInitiatedSyncManually = Notification.Name("UserInitiatedSyncManually") public static let BookmarkBufferValidated = Notification.Name("BookmarkBufferValidated") public static let FaviconDidLoad = Notification.Name("FaviconDidLoad") public static let ReachabilityStatusChanged = Notification.Name("ReachabilityStatusChanged") public static let HomePanelPrefsChanged = Notification.Name("HomePanelPrefsChanged") public static let FileDidDownload = Notification.Name("FileDidDownload") public static let DisplayThemeChanged = Notification.Name("DisplayThemeChanged") }
cdbc545a6b31da1a5c847a0cd417c746
51.786885
124
0.800621
false
false
false
false
shaoyihe/100-Days-of-IOS
refs/heads/master
14 - JUMPBAR/14 - JUMPBAR/ViewController.swift
mit
1
// // ViewController.swift // 14 - JUMPBAR // // Created by heshaoyi on 4/2/16. // Copyright © 2016 heshaoyi. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! @IBOutlet var stackView: UIStackView! var movieStore: MovieStore = MovieStore() override func loadView() { super.loadView() let height = navigationController?.navigationBar.frame.height let statusHei = UIApplication.sharedApplication().statusBarFrame.height let inset = UIEdgeInsets(top: height! + statusHei, left: 0, bottom: 0, right: 0) tableView.contentInset = inset tableView.scrollIndicatorInsets = inset tableView.delegate = self tableView.dataSource = self refreshIndex() // Do any additional setup after loading the view, typically from a nib. } func refreshIndex() { for i in 0 ..< movieStore.movieIndex.count{ let btn = UIButton(type: .System) btn.setTitle(String(movieStore.movieIndex[i]!), forState: .Normal) stackView.addArrangedSubview(btn) btn.addTarget(self, action: #selector(ViewController.scrollToTab(_:)), forControlEvents: .TouchDown) } } func scrollToTab(btn: UIButton) { let title = btn.titleLabel?.text! for (_, v) in movieStore.movieIndex.enumerate(){ if String(v.1) == title! { tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0 ,inSection : v.0), atScrollPosition: .Top, animated: true) } } } func numberOfSectionsInTableView(tableView: UITableView) -> Int{ return movieStore.movies.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return movieStore.movies[movieStore.movieIndex[section]!]!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("movie", forIndexPath: indexPath); let movie = movieStore.movies[movieStore.movieIndex[indexPath.section]!]![indexPath.row] cell.textLabel?.text = movie.name return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?{ return String(movieStore.movieIndex[section]!) } }
a23fbbd7b509184e35fa4f6d84500032
33.405405
129
0.651218
false
false
false
false
azu/AssertOperator
refs/heads/master
AssertOperatorTests/AssertOperatorTests.swift
mit
1
// // AssertOperatorTests.swift // AssertOperatorTests // // Created by azu on 2014/06/03. // Copyright (c) 2014年 azu. All rights reserved. // import XCTest operator infix =====> { associativity left precedence 140 } @infix func =====> (left: String, right: String){ assert(left == right) } class AssertOperatorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { "String" + "Liraral" =====> "StringLiralal" } }
3895674939d4fe2db3fce19afa47b6ad
25.033333
111
0.633803
false
true
false
false
ssnhitfkgd/baseProject
refs/heads/master
BaseProject/Classes/ViewControllers/BaseViewController/TableApiViewController.swift
unlicense
1
// // TableApiViewController.swift // BaseProject // // Created by wangyong on 15/2/2. // Copyright (c) 2015年 wang yong. All rights reserved. // import UIKit class TableApiViewController: ModelApiViewController, UITableViewDelegate, UITableViewDataSource, TableViewDelegate { var _tableView: UITableView? var _loadFooterView: UIView? var _loadHeaderView: UIRefreshControl? var _headerLoading : Bool = true var _footerLoading : Bool = true var _activityIndicator: UIActivityIndicatorView? func activityIndicator()-> UIActivityIndicatorView{ if(self._activityIndicator == nil){ self._activityIndicator = UIActivityIndicatorView() self._activityIndicator!.center = self._tableView!.center self._activityIndicator!.startAnimating() self._tableView?.addSubview(self._activityIndicator!) } return self._activityIndicator! } var _enableHeader: Bool{ set{ if(newValue) { if (self._loadHeaderView == nil || self._loadHeaderView!.superview == nil) { self._loadHeaderView = UIRefreshControl(); self._loadHeaderView!.addTarget(self, action: Selector("refreshTableView:"), forControlEvents: UIControlEvents.ValueChanged) self._loadHeaderView!.tintColor = UIColor.whiteColor();//[UIColor black75PercentColor]; self._tableView?.addSubview(self._loadHeaderView!) }else{ if (self._loadHeaderView != nil || self._loadHeaderView!.superview != nil){ self._loadHeaderView!.removeFromSuperview() self._loadHeaderView = nil } } } } get{ return self._enableHeader; } } func refreshTableView(refresh: UIRefreshControl){ if activityIndicator().isAnimating() { return; } self._headerLoading = true; NSThread.detachNewThreadSelector(Selector("loadData:"), toTarget: self, withObject: true) } var _enableFooter: Bool{ set{ self._enableFooter = newValue; if (newValue) { self._tableView!.tableFooterView = self._loadFooterView!; }else { self._tableView!.tableFooterView = nil; } } get{ return self._enableFooter; } } override func viewDidLoad() { super.viewDidLoad() self._tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain) self._tableView!.dataSource = self self._tableView!.delegate = self self.view .addSubview(self._tableView!) self._enableHeader = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func cellClass()-> AnyClass? { assert(true, "please override cellClass") return nil } //tableView delegate methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ if self._model == nil{ return 0 }else if self._model! is NSDictionary{ return 1 } return self._model!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ var identifier: NSString = "cell_single" if indexPath.row/2 == 0{ identifier = "cell_double" } var cell: AnyObject? = tableView.dequeueReusableCellWithIdentifier(identifier); if (cell == nil) { var cls: AnyClass? = cellClass() var CellClass: UITableViewCell.Type = cls as UITableViewCell.Type cell = CellClass(style:UITableViewCellStyle.Default , reuseIdentifier: identifier) } initCellView(cell!, indexPath: indexPath) return cell! as UITableViewCell; } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var item: AnyObject? = nil if self._model != nil && self._model! is NSArray{ item = self._model![indexPath.row] } else if self._model != nil && self._model! is NSDictionary{ item = self._model; } var cls: AnyClass? = cellClass() return cls!.rowHeightForObject!(item!) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ tableView.deselectRowAtIndexPath(indexPath, animated: true) } func initCellView(cell :AnyObject, indexPath: NSIndexPath){ if cell .respondsToSelector(Selector("setObject:")){ if(self._model!.count > indexPath.row) { var item: AnyObject? = nil if self._model != nil && self._model! is NSArray{ item = self._model![indexPath.row] } else if self._model != nil && self._model! is NSDictionary{ item = self._model; } if let temp_cell = cell as? TableViewDelegate { temp_cell.setObject!(item!) } } } } // func activeRefresh() { self._tableView!.setContentOffset(CGPointMake(0, -(self._tableView!.contentInset.top + 60)), animated: false); self._loadHeaderView?.beginRefreshing() self.refreshTableView(self._loadHeaderView!) _headerLoading = true } //override request override func didFinishLoad(result: NSArray) { updateUserInterface(result) super.didFinishLoad(result) self._tableView!.reloadData(); } func updateUserInterface(array: NSArray){ // //存储缓存 // if (self.loadmore == [NSNumber numberWithBool:NO]) { // if (array) { // [[MMDiskCacheCenter sharedInstance] setCache:array forKey:[self getCacheKey]]; // } // } if self._activityIndicator != nil { self._activityIndicator!.stopAnimating(); } // [_errorView removeFromSuperview]; self._enableFooter = true if array.count == 0 { if self._model == nil { //list 为空 // [self addSubErrorView]; self._tableView!.reloadData() self._enableFooter = false if _headerLoading { self._model = nil; finishLoadHeaderTableViewDataSource() // [self performSelector:@selector(finishLoadHeaderTableViewDataSource) withObject:nil afterDelay:0.01]; } return; } } if array.count < self .getPageSize(){ // self.hasMore = NO; // [self.loadMoreFooterView setPWState:PWLoadMoreDone]; // [self setEnableFooter:NO]; self._enableFooter = false }else{ // self.hasMore = YES; // [self.loadMoreFooterView setPWState:PWLoadMoreNormal]; } if(_footerLoading) { finishLoadFooterTableViewDataSource() } if(_headerLoading) { self._model = nil; finishLoadHeaderTableViewDataSource() } } func finishLoadHeaderTableViewDataSource(){ self._headerLoading = false self._loadHeaderView!.endRefreshing() // [self.refresh performSelectorOnMainThread:@selector(endRefreshing) withObject:nil waitUntilDone:NO]; self._tableView!.setContentOffset(CGPointMake(0, -64), animated: true) // [[self getTableView] setContentOffset:CGPointMake(0, -64) animated:YES]; } func finishLoadFooterTableViewDataSource(){ self._footerLoading = false; // [self.loadMoreFooterView performSelectorOnMainThread:@selector(pwLoadMoreTableDataSourceDidFinishedLoading) withObject:nil waitUntilDone:NO]; } }
2ba498ac334b1567493ff8b8107c3bd1
30.054152
151
0.553127
false
false
false
false
alexsosn/ConvNetSwift
refs/heads/master
ConvNetSwift/convnet-swift/Magicnet.swift
mit
1
/* A MagicNet takes data: a list of convnetjs.Vol(), and labels which for now are assumed to be class indeces 0..K. MagicNet then: - creates data folds for cross-validation - samples candidate networks - evaluates candidate networks on all data folds - produces predictions by model-averaging the best networks */ import Foundation class MagicNet { var data: [Vol] var labels: [Int] var trainRatio: Double var numFolds: Int var numCandidates: Int var numEpochs: Int var ensembleSize: Int var batchSizeMin: Int var batchSizeMax: Int var l2DecayMin: Int var l2DecayMax: Int var learningRateMin: Int var learningRateMax: Int var momentumMin: Double var momentumMax: Double var neuronsMin: Int var neuronsMax: Int var folds: [Fold] var candidates: [Candidate] var evaluatedCandidates: [Candidate] var uniqueLabels: [Int] var iter: Int var foldix: Int var finishFoldCallback: (()->())? var finishBatchCallback: (()->())? struct Fold { var train_ix: [Int] var test_ix: [Int] } struct Candidate { var acc: [AnyObject] var accv: Double var layerDefs: [LayerOptTypeProtocol] var trainerDef: TrainerOpt var net: Net var trainer: Trainer } init(data:[Vol] = [], labels:[Int] = [], opt:[String: AnyObject]) { // required inputs self.data = data // store these pointers to data self.labels = labels // optional inputs trainRatio = opt["trainRatio"] as? Double ?? 0.7 numFolds = opt["numFolds"] as? Int ?? 10 numCandidates = opt["numCandidates"] as? Int ?? 50 // we evaluate several in parallel // how many epochs of data to train every network? for every fold? // higher values mean higher accuracy in final results, but more expensive numEpochs = opt["numEpochs"] as? Int ?? 50 // number of best models to average during prediction. Usually higher = better ensembleSize = opt["ensembleSize"] as? Int ?? 10 // candidate parameters batchSizeMin = opt["batchSizeMin"] as? Int ?? 10 batchSizeMax = opt["batchSizeMax"] as? Int ?? 300 l2DecayMin = opt["l2DecayMin"] as? Int ?? -4 l2DecayMax = opt["l2DecayMax"] as? Int ?? 2 learningRateMin = opt["learningRateMin"] as? Int ?? -4 learningRateMax = opt["learningRateMax"] as? Int ?? 0 momentumMin = opt["momentumMin"] as? Double ?? 0.9 momentumMax = opt["momentumMax"] as? Double ?? 0.9 neuronsMin = opt["neuronsMin"] as? Int ?? 5 neuronsMax = opt["neuronsMax"] as? Int ?? 30 // computed folds = [] // data fold indices, gets filled by sampleFolds() candidates = [] // candidate networks that are being currently evaluated evaluatedCandidates = [] // history of all candidates that were fully evaluated on all folds uniqueLabels = ArrayUtils.arrUnique(labels) iter = 0 // iteration counter, goes from 0 -> numEpochs * numTrainingData foldix = 0 // index of active fold // callbacks finishFoldCallback = nil finishBatchCallback = nil // initializations if data.count > 0 { sampleFolds() sampleCandidates() } } // sets folds to a sampling of numFolds folds func sampleFolds() -> () { let N = data.count let numTrain = Int(floor(trainRatio * Double(N))) folds = [] // flush folds, if any for _ in 0 ..< numFolds { var p = randomPermutation(N) let fold = Fold( train_ix: Array(p[0 ..< numTrain]), test_ix: Array(p[numTrain ..< N])) folds.append(fold) } } // returns a random candidate network func sampleCandidate() -> Candidate { let inputDepth = data[0].w.count let numClasses = uniqueLabels.count // sample network topology and hyperparameters var layerDefs: [LayerOptTypeProtocol] = [] let layerInput = InputLayerOpt( outSx: 1, outSy: 1, outDepth: inputDepth) layerDefs.append(layerInput) let nl = Int(weightedSample([0,1,2,3], probs: [0.2, 0.3, 0.3, 0.2])!) // prefer nets with 1,2 hidden layers for _ in 0 ..< nl { // WARNING: iterator was q let ni = RandUtils.randi(neuronsMin, neuronsMax) let actarr: [ActivationType] = [.Tanh, .Maxout, .ReLU] let act = actarr[RandUtils.randi(0,3)] if RandUtils.randf(0,1) < 0.5 { let dp = RandUtils.random_js() let layerFC = FullyConnectedLayerOpt( numNeurons: ni, activation: act, dropProb: dp) layerDefs.append(layerFC) } else { let layerFC = FullyConnectedLayerOpt( numNeurons: ni, activation: act) layerDefs.append(layerFC ) } } let layerSoftmax = SoftmaxLayerOpt(numClasses: numClasses) layerDefs.append(layerSoftmax) let net = Net(layerDefs) // sample training hyperparameters let bs = RandUtils.randi(batchSizeMin, batchSizeMax) // batch size let l2 = pow(10, RandUtils.randf(Double(l2DecayMin), Double(l2DecayMax))) // l2 weight decay let lr = pow(10, RandUtils.randf(Double(learningRateMin), Double(learningRateMax))) // learning rate let mom = RandUtils.randf(momentumMin, momentumMax) // momentum. Lets just use 0.9, works okay usually ;p let tp = RandUtils.randf(0,1) // trainer type var trainerDef = TrainerOpt() if tp < 0.33 { trainerDef.method = .adadelta trainerDef.batchSize = bs trainerDef.l2Decay = l2 } else if tp < 0.66 { trainerDef.method = .adagrad trainerDef.batchSize = bs trainerDef.l2Decay = l2 trainerDef.learningRate = lr } else { trainerDef.method = .sgd trainerDef.batchSize = bs trainerDef.l2Decay = l2 trainerDef.learningRate = lr trainerDef.momentum = mom } let trainer = Trainer(net: net, options: trainerDef) // var cand = {} // cand.acc = [] // cand.accv = 0 // this will maintained as sum(acc) for convenience // cand.layerDefs = layerDefs // cand.trainerDef = trainerDef // cand.net = net // cand.trainer = trainer return Candidate(acc:[], accv: 0, layerDefs: layerDefs, trainerDef: trainerDef, net: net, trainer: trainer) } // sets candidates with numCandidates candidate nets func sampleCandidates() -> () { candidates = [] // flush, if any for _ in 0 ..< numCandidates { let cand = sampleCandidate() candidates.append(cand) } } func step() -> () { // run an example through current candidate iter += 1 // step all candidates on a random data point let fold = folds[foldix] // active fold let dataix = fold.train_ix[RandUtils.randi(0, fold.train_ix.count)] for k in 0 ..< candidates.count { var x = data[dataix] let l = labels[dataix] _ = candidates[k].trainer.train(x: &x, y: l) } // process consequences: sample new folds, or candidates let lastiter = numEpochs * fold.train_ix.count if iter >= lastiter { // finished evaluation of this fold. Get final validation // accuracies, record them, and go on to next fold. var valAcc = evalValErrors() for k in 0 ..< candidates.count { var c = candidates[k] c.acc.append(valAcc[k] as AnyObject) c.accv += valAcc[k] } iter = 0 // reset step number foldix += 1 // increment fold if finishFoldCallback != nil { finishFoldCallback!() } if foldix >= folds.count { // we finished all folds as well! Record these candidates // and sample new ones to evaluate. for k in 0 ..< candidates.count { evaluatedCandidates.append(candidates[k]) } // sort evaluated candidates according to accuracy achieved evaluatedCandidates.sort(by: { (a, b) -> Bool in return (a.accv / Double(a.acc.count)) < (b.accv / Double(b.acc.count)) }) // WARNING: not sure > or < ? // and clip only to the top few ones (lets place limit at 3*ensembleSize) // otherwise there are concerns with keeping these all in memory // if MagicNet is being evaluated for a very long time if evaluatedCandidates.count > 3 * ensembleSize { let clip = Array(evaluatedCandidates[0 ..< 3*ensembleSize]) evaluatedCandidates = clip } if finishBatchCallback != nil { finishBatchCallback!() } sampleCandidates() // begin with new candidates foldix = 0 // reset this } else { // we will go on to another fold. reset all candidates nets for k in 0 ..< candidates.count { var c = candidates[k] let net = Net(c.layerDefs) let trainer = Trainer(net: net, options: c.trainerDef) c.net = net c.trainer = trainer } } } } func evalValErrors() -> [Double] { // evaluate candidates on validation data and return performance of current networks // as simple list var vals: [Double] = [] var fold = folds[foldix] // active fold for k in 0 ..< candidates.count { let net = candidates[k].net var v = 0.0 for q in 0 ..< fold.test_ix.count { var x = data[fold.test_ix[q]] let l = labels[fold.test_ix[q]] _ = net.forward(&x) let yhat = net.getPrediction() v += (yhat == l ? 1.0 : 0.0) // 0 1 loss } v /= Double(fold.test_ix.count) // normalize vals.append(v) } return vals } // returns prediction scores for given test data point, as Vol // uses an averaged prediction from the best ensembleSize models // x is a Vol. func predictSoft(_ data: Vol) -> Vol { var data = data // forward prop the best networks // and accumulate probabilities at last layer into a an output Vol var evalCandidates: [Candidate] = [] var nv = 0 if evaluatedCandidates.count == 0 { // not sure what to do here, first batch of nets hasnt evaluated yet // lets just predict with current candidates. nv = candidates.count evalCandidates = candidates } else { // forward prop the best networks from evaluatedCandidates nv = min(ensembleSize, evaluatedCandidates.count) evalCandidates = evaluatedCandidates } // forward nets of all candidates and average the predictions var xout: Vol! var n: Int! for j in 0 ..< nv { let net = evalCandidates[j].net let x = net.forward(&data) if j==0 { xout = x n = x.w.count } else { // add it on for d in 0 ..< n { xout.w[d] += x.w[d] } } } // produce average for d in 0 ..< n { xout.w[d] /= Double(nv) } return xout } func predict(_ data: Vol) -> Int { let xout = predictSoft(data) var predictedLabel: Int if xout.w.count != 0 { let stats = maxmin(xout.w)! predictedLabel = stats.maxi } else { predictedLabel = -1 // error out } return predictedLabel } // func toJSON() -> [String: AnyObject] { // // dump the top ensembleSize networks as a list // let nv = min(ensembleSize, evaluatedCandidates.count) // var json: [String: AnyObject] = [:] // var jNets: [[String: AnyObject]] = [] // for i in 0 ..< nv { // jNets.append(evaluatedCandidates[i].net.toJSON()) // } // json["nets"] = jNets // return json // } // // func fromJSON(json: [String: AnyObject]) -> () { // let jNets: [AnyObject] = json["nets"] // ensembleSize = jNets.count // evaluatedCandidates = [] // for i in 0 ..< ensembleSize { // // var net = Net() // net.fromJSON(jNets[i]) // var dummyCandidate = [:] // dummyCandidate.net = net // evaluatedCandidates.append(dummyCandidate) // } // } // callback functions // called when a fold is finished, while evaluating a batch func onFinishFold(_ f: (()->())?) -> () { finishFoldCallback = f; } // called when a batch of candidates has finished evaluating func onFinishBatch(_ f: (()->())?) -> () { finishBatchCallback = f; } }
293fd6cc31dee92d4eddc4cb95965335
34.517949
115
0.537684
false
false
false
false
JQJoe/RxDemo
refs/heads/develop
Carthage/Checkouts/RxSwift/Rx.playground/Pages/Debugging_Operators.xcplaygroundpage/Contents.swift
apache-2.0
8
/*: > # IMPORTANT: To use **Rx.playground**: 1. Open **Rx.xcworkspace**. 1. Build the **RxSwift-macOS** scheme (**Product** → **Build**). 1. Open **Rx** playground in the **Project navigator**. 1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**). ---- [Previous](@previous) - [Table of Contents](Table_of_Contents) */ import RxSwift /*: # Debugging Operators Operators to help debug Rx code. ## `debug` Prints out all subscriptions, events, and disposals. */ example("debug") { let disposeBag = DisposeBag() var count = 1 let sequenceThatErrors = Observable<String>.create { observer in observer.onNext("🍎") observer.onNext("🍐") observer.onNext("🍊") if count < 5 { observer.onError(TestError.test) print("Error encountered") count += 1 } observer.onNext("🐶") observer.onNext("🐱") observer.onNext("🐭") observer.onCompleted() return Disposables.create() } sequenceThatErrors .retry(3) .debug() .subscribe(onNext: { print($0) }) .addDisposableTo(disposeBag) } /*: ---- ## `RxSwift.Resources.total` Provides a count of all Rx resource allocations, which is useful for detecting leaks during development. */ #if NOT_IN_PLAYGROUND #else example("RxSwift.Resources.total") { print(RxSwift.Resources.total) let disposeBag = DisposeBag() print(RxSwift.Resources.total) let variable = Variable("🍎") let subscription1 = variable.asObservable().subscribe(onNext: { print($0) }) print(RxSwift.Resources.total) let subscription2 = variable.asObservable().subscribe(onNext: { print($0) }) print(RxSwift.Resources.total) subscription1.dispose() print(RxSwift.Resources.total) subscription2.dispose() print(RxSwift.Resources.total) } print(RxSwift.Resources.total) #endif //: > `RxSwift.Resources.total` is not enabled by default, and should generally not be enabled in Release builds. [Click here](Enable_RxSwift.Resources.total) for instructions on how to enable it. //: [Next](@next) - [Table of Contents](Table_of_Contents)
d3f9a99a217d8f5491ea45dd5919ec39
26.26506
196
0.621741
false
false
false
false
bravelocation/yeltzland-ios
refs/heads/main
YeltzlandWidget/Views/InProgressView.swift
mit
1
// // InProgressView.swift // YeltzlandWidgetExtension // // Created by John Pollard on 12/06/2022. // Copyright © 2022 John Pollard. All rights reserved. // import WidgetKit import SwiftUI struct InProgressView: View { var data: WidgetTimelineData @Environment(\.widgetFamily) var widgetFamily var body: some View { VStack { Group { if data.first != nil { if widgetFamily == .systemSmall { TimelineFixtureView(fixture: data.first!) } else { InProgressGameView(fixture: data.first!) } } else { Text("No data available") } } if data.table != nil && widgetFamily == .systemLarge { Divider().background(Color("light-blue")) TableWidgetView(table: data.table!) Spacer() } }.padding() .foregroundColor(Color("light-blue")) .background(ContainerRelativeShape().fill(Color("yeltz-blue"))) } } #if DEBUG struct InProgressView_Previews: PreviewProvider { static var previews: some View { InProgressView(data: WidgetTimelineData( date: Date(), first: PreviewTimelineManager.buildPlaceholder(opponent: "Barnet (FAT QF)", home: false, date: "2020-02-29 15:00", teamScore: 2, opponentScore: 1, status: .inProgress), second: PreviewTimelineManager.buildPlaceholder(opponent: "Concord Rangers (FAT SF)", home: false, date: "2020-09-05 15:00", teamScore: nil, opponentScore: nil, status: .fixture), table: LeagueTableDataProvider.shared.table )).previewContext(WidgetPreviewContext(family: .systemSmall)) InProgressView(data: WidgetTimelineData( date: Date(), first: PreviewTimelineManager.buildPlaceholder(opponent: "Barnet (FAT QF)", home: false, date: "2020-02-29 15:00", teamScore: 0, opponentScore: 1, status: .inProgress), second: PreviewTimelineManager.buildPlaceholder(opponent: "Concord Rangers (FAT SF)", home: false, date: "2020-09-05 15:00", teamScore: nil, opponentScore: nil, status: .fixture), table: LeagueTableDataProvider.shared.table )).previewContext(WidgetPreviewContext(family: .systemMedium)) InProgressView(data: WidgetTimelineData( date: Date(), first: PreviewTimelineManager.buildPlaceholder(opponent: "Barnet (FAT QF)", home: false, date: "2020-02-29 15:00", teamScore: 0, opponentScore: 1, status: .inProgress), second: PreviewTimelineManager.buildPlaceholder(opponent: "Concord Rangers (FAT SF)", home: false, date: "2020-09-05 15:00", teamScore: nil, opponentScore: nil, status: .fixture), table: LeagueTableDataProvider.shared.table )).previewContext(WidgetPreviewContext(family: .systemLarge)) } } #endif
85bcd95d6b63ba2d3e4527885df04b16
41.05102
97
0.449891
false
false
false
false
zhixingxi/JJA_Swift
refs/heads/master
JJA_Swift/Pods/TimedSilver/Sources/UIKit/UIImage+TSOrientation.swift
mit
1
// // UIImage+Orientation.swift // TimedSilver // Source: https://github.com/hilen/TimedSilver // // Created by Hilen on 2/17/16. // Copyright © 2016 Hilen. All rights reserved. // import Foundation import UIKit import QuartzCore import CoreGraphics import Accelerate //https://github.com/cosnovae/fixUIImageOrientation/blob/master/fixImageOrientation.swift public extension UIImage { /** Fix the image's orientation - parameter src: the source image - returns: new image */ class func ts_fixImageOrientation(_ src:UIImage) -> UIImage { if src.imageOrientation == UIImageOrientation.up { return src } var transform: CGAffineTransform = CGAffineTransform.identity switch src.imageOrientation { case UIImageOrientation.down, UIImageOrientation.downMirrored: transform = transform.translatedBy(x: src.size.width, y: src.size.height) transform = transform.rotated(by: CGFloat(M_PI)) break case UIImageOrientation.left, UIImageOrientation.leftMirrored: transform = transform.translatedBy(x: src.size.width, y: 0) transform = transform.rotated(by: CGFloat(M_PI_2)) break case UIImageOrientation.right, UIImageOrientation.rightMirrored: transform = transform.translatedBy(x: 0, y: src.size.height) transform = transform.rotated(by: CGFloat(-M_PI_2)) break case UIImageOrientation.up, UIImageOrientation.upMirrored: break } switch src.imageOrientation { case UIImageOrientation.upMirrored, UIImageOrientation.downMirrored: transform.translatedBy(x: src.size.width, y: 0) transform.scaledBy(x: -1, y: 1) break case UIImageOrientation.leftMirrored, UIImageOrientation.rightMirrored: transform.translatedBy(x: src.size.height, y: 0) transform.scaledBy(x: -1, y: 1) case UIImageOrientation.up, UIImageOrientation.down, UIImageOrientation.left, UIImageOrientation.right: break } let ctx:CGContext = CGContext(data: nil, width: Int(src.size.width), height: Int(src.size.height), bitsPerComponent: src.cgImage!.bitsPerComponent, bytesPerRow: 0, space: src.cgImage!.colorSpace!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! ctx.concatenate(transform) switch src.imageOrientation { case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored: ctx.draw(src.cgImage!, in: CGRect(x: 0, y: 0, width: src.size.height, height: src.size.width)) break default: ctx.draw(src.cgImage!, in: CGRect(x: 0, y: 0, width: src.size.width, height: src.size.height)) break } let cgimage:CGImage = ctx.makeImage()! let image:UIImage = UIImage(cgImage: cgimage) return image } }
5fab3e0bfaaad1f2acb201ae976989cd
34.930233
262
0.646278
false
false
false
false
jholsapple/TIY-Assignments
refs/heads/master
27 -- SwiftTeams -- John Holsapple/27 -- SwiftTeams -- John Holsapple/TeamsTableViewController.swift
cc0-1.0
2
// // TeamsTableViewController.swift // 27 -- SwiftTeams -- John Holsapple // // Created by John Holsapple on 7/21/15. // Copyright (c) 2015 John Holsapple -- The Iron Yard. All rights reserved. // import UIKit class TeamsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false let moreData = [[]] var teamStorage = []() for more in moreData { let aTeam = []() aTeam.teamName = "teamName" aTeam.league = "league" aTeam.starPlayer = "starPlayer" aTeam.wins = ("wins") } } func loadTeams() { let filePath = NSBundle.mainBundle().pathForResource("Teams", ofType: "json") let teamsFromFile = NSJSONSerialization.JSONObjectWithData(NSData.dataWithContentsOfMappedFile(filePath!), options: NSJSONReadingOptions(), error: nil); -> anyobject? for agentDict in teamsFromFile { Team *anotherTeam = Team teamWithDictionary } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TeamCell", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
60d1cdf5e1395b72022e840cce1028d2
30.98374
174
0.652008
false
false
false
false
ps2/rileylink_ios
refs/heads/dev
MinimedKitTests/MinimedPumpManagerTests.swift
mit
1
// // MinimedPumpManagerTests.swift // MinimedKitTests // // Created by Pete Schwamb on 5/3/20. // Copyright © 2020 Pete Schwamb. All rights reserved. // import XCTest import RileyLinkBLEKit @testable import MinimedKit import LoopKit class MinimedPumpManagerTests: XCTestCase { var rlProvider: MockRileyLinkProvider! var mockPumpManagerDelegate: MockPumpManagerDelegate! var pumpManager: MinimedPumpManager! override func setUpWithError() throws { let device = MockRileyLinkDevice() rlProvider = MockRileyLinkProvider(devices: [device]) let rlManagerState = RileyLinkConnectionState(autoConnectIDs: []) let state = MinimedPumpManagerState( isOnboarded: true, useMySentry: true, pumpColor: .blue, pumpID: "123456", pumpModel: .model523, pumpFirmwareVersion: "VER 2.4A1.1", pumpRegion: .northAmerica, rileyLinkConnectionState: rlManagerState, timeZone: .currentFixed, suspendState: .resumed(Date()), insulinType: .novolog, lastTuned: nil, lastValidFrequency: nil) let pumpOps = MockPumpOps(pumpState: state.pumpState, pumpSettings: state.pumpSettings) pumpManager = MinimedPumpManager(state: state, rileyLinkDeviceProvider: rlProvider, pumpOps: pumpOps) mockPumpManagerDelegate = MockPumpManagerDelegate() pumpManager.pumpManagerDelegate = mockPumpManagerDelegate } func testBolusWithInvalidResponse() { let exp = expectation(description: "enactBolus callback") pumpManager.enactBolus(units: 2.3, activationType: .manualNoRecommendation) { error in XCTAssertNotNil(error) exp.fulfill() } waitForExpectations(timeout: 2) } }
8cc7490a7679621d08b32eeb33348a09
34.288462
109
0.675749
false
true
false
false
GrafixMafia/SpaceState
refs/heads/master
spacestate/FirstViewController.swift
mit
1
// // FirstViewController.swift // spacestate // // Created by markus on 23.08.14. // Copyright (c) 2014 grafixmafia.net. All rights reserved. // import UIKit class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var refreshControl: UIRefreshControl! var statusHandler : StatusHandler? var items: [String] = ["We", "blub"] override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") statusHandler = StatusHandler() refreshControl = UIRefreshControl() refreshControl.attributedTitle = NSAttributedString(string: "Checking State") refreshControl.addTarget(self, action: #selector(FirstViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(refreshControl) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell cell.textLabel?.text = self.items[indexPath.row] return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count; } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("You selected cell #\(indexPath.row)!") } func refresh(sender:AnyObject) { print("pull") refreshControl.endRefreshing(); } }
744eced2778e626117d796c8aa68957b
29.190476
138
0.667718
false
false
false
false
sahandnayebaziz/StateView
refs/heads/master
StateView/ShadowViewElement.swift
mit
1
// // ShadowViewElement.swift // StateView // // Created by Sahand Nayebaziz on 4/3/16. // Copyright © 2016 Sahand Nayebaziz. All rights reserved. // import UIKit import SnapKit protocol ShadowElement: Equatable { var key: String { get set } var viewHash: String? { get set } var containingView: StateView { get set } var constraints: ((_ make: ConstraintMaker) -> Void) { get set } var getInitializedViewWithParentViewController: ((UIViewController) -> UIView) { get set } } // a generic class used to Super-connect ShadowViewElement and ShadowStateViewElement open class ShadowGenericElement: ShadowElement { var key: String var viewHash: String? var containingView: StateView var constraints: ((_ make: ConstraintMaker) -> Void) var getInitializedViewWithParentViewController: ((UIViewController) -> UIView) init(key: String, containingView: StateView, constraints: @escaping ((_ make: ConstraintMaker) -> Void)) { self.key = key self.viewHash = nil self.containingView = containingView self.constraints = constraints self.getInitializedViewWithParentViewController = { _ in return UIView() } } } public func ==(lhs: ShadowGenericElement, rhs: ShadowGenericElement) -> Bool { if let lhsState = lhs as? ShadowStateViewElement, let rhsState = rhs as? ShadowStateViewElement { return lhsState.key == rhsState.key && lhsState.containingView == rhsState.containingView && lhsState.type == rhsState.type } else if let lhsView = lhs as? ShadowViewElement, let rhsView = rhs as? ShadowViewElement { return lhsView.key == rhsView.key && lhsView.containingView == rhsView.containingView && lhsView.view == rhsView.view } else { return lhs.key == rhs.key && lhs.containingView == rhs.containingView } } open class ShadowViewElement: ShadowGenericElement { var view: UIView init(key: String, containingView: StateView, constraints: @escaping ((_ make: ConstraintMaker) -> Void), view: UIView) { self.view = view super.init(key: key, containingView: containingView, constraints: constraints) self.getInitializedViewWithParentViewController = { _ in return view } } } open class ShadowStateViewElement: ShadowGenericElement { var type: StateView.Type var props: [StateViewProp] var firstTimeReceivingProps = true init(key: String, containingView: StateView, constraints: @escaping ((_ make: ConstraintMaker) -> Void), type: StateView.Type) { self.type = type self.props = [] super.init(key: key, containingView: containingView, constraints: constraints) self.getInitializedViewWithParentViewController = { parentViewController in return type.init(parentViewController: parentViewController) } } open func prop(forKey key: StateKey, is value: Any) { containingView.setProp(self, toValue: value, forKey: key) } open func prop(forKey key: StateKey, isLinkedToKeyInState stateKey: String) { containingView.setProp(self, toStateKey: stateKey, forKey: key) } open func prop(forKey key: StateKey, isFunction function: @escaping (([String: Any])->Void)) { containingView.setProp(self, forKey: key, toFunction: function) } func setProps(_ props: [StateViewProp]) { self.props = props } }
a1b1015b8f4f21642eca7cbf81aeb892
35.40625
132
0.676681
false
false
false
false
ps2/rileylink_ios
refs/heads/dev
OmniKit/OmnipodCommon/MessageBlocks/PodInfoResponse.swift
mit
1
// // PodInfoResponse.swift // OmniKit // // Created by Pete Schwamb on 2/23/18. // Copyright © 2018 Pete Schwamb. All rights reserved. // import Foundation public struct PodInfoResponse : MessageBlock { public let blockType : MessageBlockType = .podInfoResponse public let podInfoResponseSubType : PodInfoResponseSubType public let podInfo : PodInfo public let data : Data public init(encodedData: Data) throws { guard let subType = PodInfoResponseSubType(rawValue: encodedData[2]) else { throw MessageError.unknownValue(value: encodedData[2], typeDescription: "PodInfoResponseSubType") } self.podInfoResponseSubType = subType let len = encodedData.count podInfo = try podInfoResponseSubType.podInfoType.init(encodedData: encodedData.subdata(in: 2..<len)) self.data = encodedData } } extension PodInfoResponse: CustomDebugStringConvertible { public var debugDescription: String { return "PodInfoResponse(\(blockType), \(podInfoResponseSubType), \(podInfo)" } }
96bf3b27d87dc4d1f5bc7f63364c0294
31.882353
109
0.684258
false
false
false
false
auth0/Lock.swift
refs/heads/master
LockTests/Interactors/MultifactorInteractorSpec.swift
mit
1
// MultifactorInteractorSpec.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Quick import Nimble import OHHTTPStubs #if SWIFT_PACKAGE import OHHTTPStubsSwift #endif import Auth0 @testable import Lock class MultifactorInteractorSpec: QuickSpec { override func spec() { var user: User! var interactor: MultifactorInteractor! var connection: DatabaseConnection! var credentials: Credentials? var options: OptionBuildable! beforeEach { user = User() user.email = email user.validEmail = true user.password = password user.validPassword = true options = LockOptions() credentials = nil var dispatcher = ObserverStore() dispatcher.onAuth = { credentials = $0 } connection = DatabaseConnection(name: "myConnection", requiresUsername: true) interactor = MultifactorInteractor(user: user, authentication: Auth0.authentication(clientId: clientId, domain: domain), connection: connection, options: options, dispatcher: dispatcher) } describe("OOB challenge") { let mfaToken = "VALID_TOKEN" describe("start challenge") { it("should yield challenge on success") { let challengeType = "oob" let oobCode = "oob:\(UUID().uuidString)" let bindingMethod = "binding method" stub(condition: mfaChallengeStart(mfaToken: mfaToken)) { _ in return Auth0Stubs.multifactorChallenge(challengeType: challengeType, oobCode: oobCode, bindingMethod: bindingMethod) } waitUntil(timeout: .seconds(2)) { done in interactor.startMultifactorChallenge(mfaToken: mfaToken) { _ in expect(interactor.challenge?.challengeType) == challengeType expect(interactor.challenge?.oobCode) == oobCode expect(interactor.challenge?.bindingMethod) == bindingMethod done() } } } it("should yield error on failure") { stub(condition: mfaChallengeStart(mfaToken: mfaToken)) { _ in return Auth0Stubs.failure() } waitUntil(timeout: .seconds(2)) { done in interactor.startMultifactorChallenge(mfaToken: mfaToken) { _ in expect(interactor.challenge).to(beNil()) done() } } } } } describe("updateCode") { it("should update code") { expect{ try interactor.setMultifactorCode(code) }.toNot(throwError()) expect(interactor.code) == code } it("should trim email") { expect{ try interactor.setMultifactorCode(" \(code) ") }.toNot(throwError()) expect(interactor.code) == code } it("should set valid flag") { let _ = try? interactor.setMultifactorCode(code) expect(interactor.validCode) == true } describe("code validation") { it("should set valid flag") { let _ = try? interactor.setMultifactorCode("not a code") expect(interactor.validCode) == false } it("should always store value") { let _ = try? interactor.setMultifactorCode("not a code") expect(interactor.code) == "not a code" } it("should raise error if code is invalid") { expect{ try interactor.setMultifactorCode("not an email") }.to(throwError(InputValidationError.notAOneTimePassword)) } it("should raise error if code is empty") { expect{ try interactor.setMultifactorCode("") }.to(throwError(InputValidationError.mustNotBeEmpty)) } it("should raise error if email is only spaces") { expect{ try interactor.setMultifactorCode(" ") }.to(throwError(InputValidationError.mustNotBeEmpty)) } it("should raise error if email is nil") { expect{ try interactor.setMultifactorCode(nil) }.to(throwError(InputValidationError.mustNotBeEmpty)) } } } describe("login") { beforeEach { options.oidcConformant = false var dispatcher = ObserverStore() dispatcher.onAuth = { credentials = $0 } interactor = MultifactorInteractor(user: user, authentication: Auth0.authentication(clientId: clientId, domain: domain), connection: connection, options: options, dispatcher: dispatcher) } it("should yield no error on success") { stub(condition: databaseLogin(identifier: email, password: password, code: code, connection: connection.name)) { _ in return Auth0Stubs.authentication() } try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error).to(beNil()) done() } } } it("should yield credentials") { stub(condition: databaseLogin(identifier: email, password: password, code: code, connection: connection.name)) { _ in return Auth0Stubs.authentication() } try! interactor.setMultifactorCode(code) interactor.login { _ in } expect(credentials).toEventuallyNot(beNil()) } it("should yield error on failure") { stub(condition: databaseLogin(identifier: email, password: password, code: code, connection: connection.name)) { _ in return Auth0Stubs.failure() } try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error) == .couldNotLogin done() } } } it("should notify when code is invalid") { stub(condition: databaseLogin(identifier: email, password: password, code: code, connection: connection.name)) { _ in return Auth0Stubs.failure("a0.mfa_invalid_code") } try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error) == .multifactorInvalid done() } } } it("should yield error when input is not valid") { waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error) == .nonValidInput done() } } } it("should indicate that a custom rule prevented the user from logging in") { stub(condition: databaseLogin(identifier: email, password: password, code: code, connection: connection.name)) { _ in return Auth0Stubs.failure("unauthorized", description: "Only admins can use this") } try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error) == .customRuleFailure(cause: "Only admins can use this") done() } } } } describe("login OIDC") { var dispatcher = ObserverStore() let mfaToken = "VALID_TOKEN" beforeEach { options.oidcConformant = true dispatcher.onAuth = { credentials = $0 } interactor = MultifactorInteractor(user: user, authentication: Auth0.authentication(clientId: clientId, domain: domain), connection: connection, options: options, dispatcher: dispatcher, mfaToken: mfaToken) } it("should yield no error on success") { stub(condition: otpLogin(otp: code, mfaToken: mfaToken)) { _ in return Auth0Stubs.authentication() } try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error).to(beNil()) done() } } } it("should yield credentials") { stub(condition: otpLogin(otp: code, mfaToken: mfaToken)) { _ in return Auth0Stubs.authentication() } try! interactor.setMultifactorCode(code) interactor.login { _ in } expect(credentials).toEventuallyNot(beNil()) } it("should yield error when not token set") { interactor = MultifactorInteractor(user: user, authentication: Auth0.authentication(clientId: clientId, domain: domain), connection: connection, options: options, dispatcher: dispatcher, mfaToken: nil) try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error) == .couldNotLogin done() } } } it("should notify when code is invalid") { interactor = MultifactorInteractor(user: user, authentication: Auth0.authentication(clientId: clientId, domain: domain), connection: connection, options: options, dispatcher: dispatcher, mfaToken: "INVALID_TOKEN") stub(condition: otpLogin(otp: code, mfaToken: "INVALID_TOKEN")) { _ in return Auth0Stubs.failure("a0.mfa_invalid_code") } try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error) == .multifactorInvalid done() } } } it("should yield error when input is not valid") { waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error) == .nonValidInput done() } } } it("should indicate that a custom rule prevented the user from logging in") { stub(condition: otpLogin(otp: code, mfaToken: mfaToken)) { _ in return Auth0Stubs.failure("unauthorized", description: "Only admins can use this") } try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error) == .customRuleFailure(cause: "Only admins can use this") done() } } } describe("OOB challenge code") { beforeEach { let oobCode = "oob:\(UUID().uuidString)" stub(condition: mfaChallengeStart(mfaToken: mfaToken)) { _ in return Auth0Stubs.multifactorChallenge(challengeType: "oob", oobCode: oobCode) } stub(condition: oobLogin(oob: oobCode, mfaToken: mfaToken, bindingCode: code)) { _ in return Auth0Stubs.authentication() } } it("should yield no error on success") { waitUntil(timeout: .seconds(2)) { done in interactor.startMultifactorChallenge(mfaToken: mfaToken) { _ in done() } } try! interactor.setMultifactorCode(code) waitUntil(timeout: .seconds(2)) { done in interactor.login { error in expect(error).to(beNil()) done() } } } it("should yield credentials") { waitUntil(timeout: .seconds(2)) { done in interactor.startMultifactorChallenge(mfaToken: mfaToken) { _ in done() } } try! interactor.setMultifactorCode(code) interactor.login { _ in } expect(credentials).toEventuallyNot(beNil()) } } } } }
4250aaa20931ad2ec7bc1c710035edda
43.927673
229
0.535102
false
false
false
false
azarovalex/Simple-Ciphers
refs/heads/master
Theory Of Information, Lab 1/ViewController.swift
mit
1
// // ViewController.swift // Theory Of Information, Lab 1 // // Created by Alex Azarov on 15/09/2017. // Copyright © 2017 Alex Azarov. All rights reserved. // import Cocoa var path: String = "" func browseFile() -> String { let dialog = NSOpenPanel(); dialog.title = "Choose a .txt file"; dialog.showsResizeIndicator = true; dialog.showsHiddenFiles = false; dialog.canChooseDirectories = true; dialog.canCreateDirectories = true; dialog.allowsMultipleSelection = false; dialog.allowedFileTypes = ["txt"]; if (dialog.runModal() == NSApplication.ModalResponse.OK) { let result = dialog.url // Pathname of the file if (result != nil) { path = result!.path return path } } else { // User clicked on "Cancel" return "" } return "" } class ViewController: NSViewController { var fileURL = URL(fileURLWithPath: "/") @IBOutlet weak var plaintextField: NSTextField! @IBOutlet weak var railfenceField: NSTextField! @IBOutlet weak var ciphertextField: NSTextField! @IBOutlet weak var keysizeLabel: NSTextField! @IBOutlet weak var keyField: NSTextField! @IBOutlet weak var symbolsCheckbox: NSButton! var ciphertext = "" var plaintext = "" var railfence = "" var sizeofkey = 0 override func viewDidLoad() { super.viewDidLoad() symbolsCheckbox.state = .off } // FINISHED @IBAction func loadText(_ sender: NSButton) { fileURL = URL(fileURLWithPath: browseFile()) switch sender.tag { case 1: do { plaintextField.stringValue = try String(contentsOf: fileURL) } catch { dialogError(question: "Failed reading from URL: \(fileURL)", text: "Error: " + error.localizedDescription) } case 2: do { ciphertextField.stringValue = try String(contentsOf: fileURL) } catch { dialogError(question: "Failed reading from URL: \(fileURL)", text: "Error: " + error.localizedDescription) } default: break } } @IBAction func storeText(_ sender: NSButton) { fileURL = URL(fileURLWithPath: browseFile()) switch sender.tag { case 1: do { try plaintextField.stringValue.write(to: fileURL, atomically: true, encoding: .utf8) } catch { dialogError(question: "Failed writing to URL \(fileURL)", text: "Error: " + error.localizedDescription) } case 2: do { try ciphertextField.stringValue.write(to: fileURL, atomically: true, encoding: .utf8) } catch { dialogError(question: "Failed writing to URL \(fileURL)", text: "Error: " + error.localizedDescription) } default: break } } // FINISHED @IBAction func encodeBtnPressed(_ sender: Any) { plaintext = plaintextField.stringValue guard plaintext != "" else { dialogError(question: "Your plaintext is an empty string!", text: "Error: Nothing to encipher.") return } // Get sizeofkey var keyStr = keyField.stringValue keyStr = keyStr.components(separatedBy: CharacterSet.decimalDigits.inverted).joined() keyField.stringValue = keyStr if (keyStr == "") { dialogError(question: "Key field is empty!", text: "Error: Can not encipher without a key.") return } sizeofkey = Int(keyStr)! if (sizeofkey == 0) { dialogError(question: "Not a valid key!", text: "Error: Can not encipher with zero hight.") return } // Save special characters // if symbolsCheckbox.state == .on { plaintext = String(cString: SaveSpecialSymbols(plaintext)) // } else { // plaintext = plaintext.components(separatedBy: CharacterSet.letters.inverted).joined() // plaintextField.stringValue = plaintext // } // Draw the rail fence railfence = String(cString: MakeRailFence(plaintext, Int32(plaintext.count), Int32(sizeofkey))) railfenceField.stringValue = railfence // Load special characters and display ciphertext ciphertext = String(cString: Encipher(railfence, Int32(plaintext.count))) if symbolsCheckbox.state == .on { // ciphertext = String(cString: ReturnSpecialSymbols(ciphertext)) } ciphertextField.stringValue = ciphertext } @IBAction func decodeBtnPressed(_ sender: Any) { ciphertext = ciphertextField.stringValue guard ciphertext != "" else { dialogError(question: "Your ciphertext is an empy string!", text: "Error: Nothing to encipher.") return } // Get sizeofkey var keyStr = keyField.stringValue keyStr = keyStr.components(separatedBy: CharacterSet.decimalDigits.inverted).joined() keyField.stringValue = keyStr if (keyStr == "") { dialogError(question: "Key field is empty!", text: "Error: Can not decipher without a key.") return } sizeofkey = Int(keyStr)! if (sizeofkey == 0) { dialogError(question: "Not a valid key!", text: "Error: Can not decipher with zero hight.") return } if symbolsCheckbox.state == .on { ciphertext = String(cString: SaveSpecialSymbols(ciphertext)) } else { ciphertext = ciphertext.components(separatedBy: CharacterSet.letters.inverted).joined() ciphertextField.stringValue = ciphertext } plaintext = String(cString: Decipher(ciphertext, Int32(sizeofkey))); if symbolsCheckbox.state == .on { plaintext = String(cString: ReturnSpecialSymbols(plaintext)) } plaintextField.stringValue = plaintext railfence = String(cString: MakeRailFence(plaintext, Int32(plaintext.count), Int32(sizeofkey))) railfenceField.stringValue = railfence } }
07347202c3f0d108a40308b36372ef64
32.978723
122
0.584534
false
false
false
false
dduan/swift
refs/heads/master
test/attr/attr_objc.swift
apache-2.0
1
// RUN: %target-parse-verify-swift // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module | FileCheck %s // RUN: not %target-swift-frontend -parse -dump-ast -disable-objc-attr-requires-foundation-module %s 2> %t.dump // RUN: FileCheck -check-prefix CHECK-DUMP %s < %t.dump // REQUIRES: objc_interop import Foundation class PlainClass {} struct PlainStruct {} enum PlainEnum {} protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}} @objc class Class_ObjC1 {} protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}} protocol Protocol_Class2 : class {} @objc protocol Protocol_ObjC1 {} @objc protocol Protocol_ObjC2 {} //===--- Subjects of @objc attribute. @objc extension PlainClass { } // expected-error{{@objc cannot be applied to this declaration}}{{1-7=}} @objc var subject_globalVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} var subject_getterSetter: Int { @objc get { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} return 0 } @objc set { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } } var subject_global_observingAccessorsVar1: Int = 0 { @objc willSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} } @objc didSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} } } class subject_getterSetter1 { var instanceVar1: Int { @objc get { // expected-error {{'@objc' getter for non-'@objc' property}} return 0 } } var instanceVar2: Int { get { return 0 } @objc set { // expected-error {{'@objc' setter for non-'@objc' property}} } } var instanceVar3: Int { @objc get { // expected-error {{'@objc' getter for non-'@objc' property}} return 0 } @objc set { // expected-error {{'@objc' setter for non-'@objc' property}} } } var observingAccessorsVar1: Int = 0 { @objc willSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}} } @objc didSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}} } } } class subject_staticVar1 { @objc class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}} @objc class var staticVar2: Int { return 42 } } @objc func subject_freeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}} @objc var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc func subject_nestedFreeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } } @objc func subject_genericFunc<T>(t: T) { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}} @objc var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}} } @objc // expected-error {{@objc cannot be applied to this declaration}} {{1-7=}} struct subject_struct { @objc var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } @objc // expected-error {{@objc cannot be applied to this declaration}} {{1-7=}} struct subject_genericStruct<T> { @objc var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} @objc func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } @objc class subject_class1 { // no-error @objc var subject_instanceVar: Int // no-error @objc init() {} // no-error @objc func subject_instanceFunc() {} // no-error } @objc class subject_class2 : Protocol_Class1, PlainProtocol { // no-error } @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{1-7=}} class subject_genericClass<T> { @objc var subject_instanceVar: Int // no-error @objc init() {} // no-error @objc func subject_instanceFunc() {} // no_error } @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{1-7=}} class subject_genericClass2<T> : Class_ObjC1 { @objc var subject_instanceVar: Int // no-error @objc init(foo: Int) {} // no-error @objc func subject_instanceFunc() {} // no_error } extension subject_genericClass where T : Hashable { @objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}} } extension subject_genericClass { @objc var extProp: Int { return 0 } // expected-error{{@objc is not supported within extensions of generic classes}} @objc func extFoo() {} // expected-error{{@objc is not supported within extensions of generic classes}} } @objc enum subject_enum: Int { @objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}} case subject_enumElement1 @objc(subject_enumElement2) case subject_enumElement2 @objc(subject_enumElement3) case subject_enumElement3, subject_enumElement4 // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-8=}} @objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}} case subject_enumElement5, subject_enumElement6 @nonobjc // expected-error {{@nonobjc cannot be applied to this declaration}} case subject_enumElement7 @objc init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} @objc func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}} } enum subject_enum2 { @objc(subject_enum2Element1) case subject_enumElement1 // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-8=}} } @objc protocol subject_protocol1 { @objc var subject_instanceVar: Int { get } @objc func subject_instanceFunc() } @objc protocol subject_protocol2 {} // no-error // CHECK-LABEL: @objc protocol subject_protocol2 { @objc protocol subject_protocol3 {} // no-error // CHECK-LABEL: @objc protocol subject_protocol3 { @objc protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}} @objc protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}} @objc protocol subject_protocol6 : Protocol_ObjC1 {} protocol subject_containerProtocol1 { @objc var subject_instanceVar: Int { get } // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc func subject_instanceFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc static func subject_staticFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} } @objc protocol subject_containerObjCProtocol1 { func func_FunctionReturn1() -> PlainStruct // expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} func func_FunctionParam1(a: PlainStruct) // expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} func func_Variadic(_: AnyObject...) // expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}} // expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}} subscript(a: PlainStruct) -> Int { get } // expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} var varNonObjC1: PlainStruct { get } // expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} } @objc protocol subject_containerObjCProtocol2 { init(a: Int) @objc init(a: Double) func func1() -> Int @objc func func1_() -> Int var instanceVar1: Int { get set } @objc var instanceVar1_: Int { get set } subscript(i: Int) -> Int { get set } @objc subscript(i: String) -> Int { get set} } protocol nonObjCProtocol { @objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} } func concreteContext1() { @objc class subject_inConcreteContext {} } class ConcreteContext2 { @objc class subject_inConcreteContext {} } class ConcreteContext3 { func dynamicSelf1() -> Self { return self } @objc func dynamicSelf1_() -> Self { return self } // expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} @objc func genericParams<T: NSObject>() -> [T] { return [] } // expected-error@-1{{method cannot be marked @objc because it has generic parameters}} } func genericContext1<T>(_: T) { @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{3-9=}} class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' nested in generic function 'genericContext1' is not allowed}} @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{3-9=}} class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' nested in generic function 'genericContext1' is not allowed}} class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' nested in generic function 'genericContext1' is not allowed}} @objc init() {} // no-error } class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' nested in generic function 'genericContext1' is not allowed}} @objc var subject_instanceVar: Int = 0 // no-error } class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' nested in generic function 'genericContext1' is not allowed}} @objc func f() {} // no-error } } class GenericContext2<T> { @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{3-9=}} class subject_inGenericContext {} // expected-error{{nested in generic type}} @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{3-9=}} class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{nested in generic type}} @objc func f() {} // no-error } class GenericContext3<T> { class MoreNested { // expected-error{{nested in generic type}} @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{5-11=}} class subject_inGenericContext {} // expected-error{{nested in generic type}} @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{5-11=}} class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{nested in generic type}} @objc func f() {} // no-error } } @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{1-7=}} class ConcreteSubclassOfGeneric : GenericContext3<Int> {} extension ConcreteSubclassOfGeneric { @objc func foo() {} // expected-error {{@objc is not supported within extensions of generic classes}} } @objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{1-7=}} class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {} extension ConcreteSubclassOfGeneric2 { @objc func foo() {} // expected-error {{@objc is not supported within extensions of generic classes}} } class subject_subscriptIndexed1 { @objc subscript(a: Int) -> Int { // no-error get { return 0 } } } class subject_subscriptIndexed2 { @objc subscript(a: Int8) -> Int { // no-error get { return 0 } } } class subject_subscriptIndexed3 { @objc subscript(a: UInt8) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed1 { @objc subscript(a: String) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed2 { @objc subscript(a: Class_ObjC1) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed3 { @objc subscript(a: Class_ObjC1.Type) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed4 { @objc subscript(a: Protocol_ObjC1) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed5 { @objc subscript(a: Protocol_ObjC1.Type) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed6 { @objc subscript(a: protocol<Protocol_ObjC1, Protocol_ObjC2>) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed7 { @objc subscript(a: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type) -> Int { // no-error get { return 0 } } } class subject_subscriptBridgedFloat { @objc subscript(a: Float32) -> Int { get { return 0 } } } class subject_subscriptGeneric<T> { @objc subscript(a: Int) -> Int { // no-error get { return 0 } } } class subject_subscriptInvalid2 { @objc subscript(a: PlainClass) -> Int { // expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid3 { @objc subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid4 { @objc subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{Swift structs cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid5 { @objc subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{enums cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid6 { @objc subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol 'PlainProtocol' is not '@objc'}} get { return 0 } } } class subject_subscriptInvalid7 { @objc subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol 'Protocol_Class1' is not '@objc'}} get { return 0 } } } class subject_subscriptInvalid8 { @objc subscript(a: protocol<Protocol_Class1, Protocol_Class2>) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol 'Protocol_Class1' is not '@objc'}} get { return 0 } } } //===--- Tests for @objc inference. @objc class infer_instanceFunc1 { // CHECK-LABEL: @objc class infer_instanceFunc1 { func func1() {} // CHECK-LABEL: @objc func func1() { @objc func func1_() {} // no-error func func2(a: Int) {} // CHECK-LABEL: @objc func func2(a: Int) { @objc func func2_(a: Int) {} // no-error func func3(a: Int) -> Int {} // CHECK-LABEL: @objc func func3(a: Int) -> Int { @objc func func3_(a: Int) -> Int {} // no-error func func4(a: Int, b: Double) {} // CHECK-LABEL: @objc func func4(a: Int, b: Double) { @objc func func4_(a: Int, b: Double) {} // no-error func func5(a: String) {} // CHECK-LABEL: @objc func func5(a: String) { @objc func func5_(a: String) {} // no-error func func6() -> String {} // CHECK-LABEL: @objc func func6() -> String { @objc func func6_() -> String {} // no-error func func7(a: PlainClass) {} // CHECK-LABEL: {{^}} func func7(a: PlainClass) { @objc func func7_(a: PlainClass) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} func func7m(a: PlainClass.Type) {} // CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) { @objc func func7m_(a: PlainClass.Type) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} func func8() -> PlainClass {} // CHECK-LABEL: {{^}} func func8() -> PlainClass { @objc func func8_() -> PlainClass {} // expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} func func8m() -> PlainClass.Type {} // CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type { @objc func func8m_() -> PlainClass.Type {} // expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} func func9(a: PlainStruct) {} // CHECK-LABEL: {{^}} func func9(a: PlainStruct) { @objc func func9_(a: PlainStruct) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} func func10() -> PlainStruct {} // CHECK-LABEL: {{^}} func func10() -> PlainStruct { @objc func func10_() -> PlainStruct {} // expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} func func11(a: PlainEnum) {} // CHECK-LABEL: {{^}} func func11(a: PlainEnum) { @objc func func11_(a: PlainEnum) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}} func func12(a: PlainProtocol) {} // CHECK-LABEL: {{^}} func func12(a: PlainProtocol) { @objc func func12_(a: PlainProtocol) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}} func func13(a: Class_ObjC1) {} // CHECK-LABEL: @objc func func13(a: Class_ObjC1) { @objc func func13_(a: Class_ObjC1) {} // no-error func func14(a: Protocol_Class1) {} // CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) { @objc func func14_(a: Protocol_Class1) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}} func func15(a: Protocol_ObjC1) {} // CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) { @objc func func15_(a: Protocol_ObjC1) {} // no-error func func16(a: AnyObject) {} // CHECK-LABEL: @objc func func16(a: AnyObject) { @objc func func16_(a: AnyObject) {} // no-error func func17(a: () -> ()) {} // CHECK-LABEL: {{^}} @objc func func17(a: () -> ()) { @objc func func17_(a: () -> ()) {} func func18(a: (Int) -> (), b: Int) {} // CHECK-LABEL: {{^}} @objc func func18(a: (Int) -> (), b: Int) @objc func func18_(a: (Int) -> (), b: Int) {} func func19(a: (String) -> (), b: Int) {} // CHECK-LABEL: {{^}} @objc func func19(a: (String) -> (), b: Int) { @objc func func19_(a: (String) -> (), b: Int) {} func func_FunctionReturn1() -> () -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () { @objc func func_FunctionReturn1_() -> () -> () {} func func_FunctionReturn2() -> (Int) -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () { @objc func func_FunctionReturn2_() -> (Int) -> () {} func func_FunctionReturn3() -> () -> Int {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int { @objc func func_FunctionReturn3_() -> () -> Int {} func func_FunctionReturn4() -> (String) -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () { @objc func func_FunctionReturn4_() -> (String) -> () {} func func_FunctionReturn5() -> () -> String {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String { @objc func func_FunctionReturn5_() -> () -> String {} func func_ZeroParams1() {} // CHECK-LABEL: @objc func func_ZeroParams1() { @objc func func_ZeroParams1a() {} // no-error func func_OneParam1(a: Int) {} // CHECK-LABEL: @objc func func_OneParam1(a: Int) { @objc func func_OneParam1a(a: Int) {} // no-error func func_TupleStyle1(a: Int, b: Int) {} // CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) { @objc func func_TupleStyle1a(a: Int, b: Int) {} func func_TupleStyle2(a: Int, b: Int, c: Int) {} // CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) { @objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {} // Check that we produce diagnostics for every parameter and return type. @objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> protocol<> {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}} // expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}} // expected-error@-5 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-6 {{'protocol<>' is not considered '@objc'; use 'AnyObject' instead}} @objc func func_UnnamedParam1(_: Int) {} // no-error @objc func func_UnnamedParam2(_: PlainStruct) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} @objc func func_varParam1(a: AnyObject) { var a = a let b = a; a = b } func func_varParam2(a: AnyObject) { var a = a let b = a; a = b } // CHECK-LABEL: @objc func func_varParam2(a: AnyObject) { } @objc class infer_constructor1 { // CHECK-LABEL: @objc class infer_constructor1 init() {} // CHECK: @objc init() init(a: Int) {} // CHECK: @objc init(a: Int) init(a: PlainStruct) {} // CHECK: {{^}} init(a: PlainStruct) init(malice: ()) {} // CHECK: @objc init(malice: ()) init(forMurder _: ()) {} // CHECK: @objc init(forMurder _: ()) } @objc class infer_destructor1 { // CHECK-LABEL: @objc class infer_destructor1 deinit {} // CHECK: @objc deinit } // @!objc class infer_destructor2 { // CHECK-LABEL: {{^}}class infer_destructor2 deinit {} // CHECK: @objc deinit } @objc class infer_instanceVar1 { // CHECK-LABEL: @objc class infer_instanceVar1 { init() {} var instanceVar1: Int // CHECK: @objc var instanceVar1: Int var (instanceVar2, instanceVar3): (Int, PlainProtocol) // CHECK: @objc var instanceVar2: Int // CHECK: {{^}} var instanceVar3: PlainProtocol @objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol) // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}} var intstanceVar4: Int { // CHECK: @objc var intstanceVar4: Int { get {} // CHECK-NEXT: @objc get {} } var intstanceVar5: Int { // CHECK: @objc var intstanceVar5: Int { get {} // CHECK-NEXT: @objc get {} set {} // CHECK-NEXT: @objc set {} } @objc var instanceVar5_: Int { // CHECK: @objc var instanceVar5_: Int { get {} // CHECK-NEXT: @objc get {} set {} // CHECK-NEXT: @objc set {} } var observingAccessorsVar1: Int { // CHECK: @objc var observingAccessorsVar1: Int { willSet {} // CHECK-NEXT: {{^}} final willSet {} didSet {} // CHECK-NEXT: {{^}} final didSet {} } @objc var observingAccessorsVar1_: Int { // CHECK: {{^}} @objc var observingAccessorsVar1_: Int { willSet {} // CHECK-NEXT: {{^}} final willSet {} didSet {} // CHECK-NEXT: {{^}} final didSet {} } var var_Int: Int // CHECK-LABEL: @objc var var_Int: Int var var_Bool: Bool // CHECK-LABEL: @objc var var_Bool: Bool var var_CBool: CBool // CHECK-LABEL: @objc var var_CBool: CBool var var_String: String // CHECK-LABEL: @objc var var_String: String var var_Float: Float var var_Double: Double // CHECK-LABEL: @objc var var_Float: Float // CHECK-LABEL: @objc var var_Double: Double var var_Char: UnicodeScalar // CHECK-LABEL: @objc var var_Char: UnicodeScalar //===--- Tuples. var var_tuple1: () // CHECK-LABEL: {{^}} var var_tuple1: () @objc var var_tuple1_: () // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{empty tuple type cannot be represented in Objective-C}} var var_tuple2: Void // CHECK-LABEL: {{^}} var var_tuple2: Void @objc var var_tuple2_: Void // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{empty tuple type cannot be represented in Objective-C}} var var_tuple3: (Int) // CHECK-LABEL: @objc var var_tuple3: (Int) @objc var var_tuple3_: (Int) // no-error var var_tuple4: (Int, Int) // CHECK-LABEL: {{^}} var var_tuple4: (Int, Int) @objc var var_tuple4_: (Int, Int) // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{tuples cannot be represented in Objective-C}} //===--- Stdlib integer types. var var_Int8: Int8 var var_Int16: Int16 var var_Int32: Int32 var var_Int64: Int64 // CHECK-LABEL: @objc var var_Int8: Int8 // CHECK-LABEL: @objc var var_Int16: Int16 // CHECK-LABEL: @objc var var_Int32: Int32 // CHECK-LABEL: @objc var var_Int64: Int64 var var_UInt8: UInt8 var var_UInt16: UInt16 var var_UInt32: UInt32 var var_UInt64: UInt64 // CHECK-LABEL: @objc var var_UInt8: UInt8 // CHECK-LABEL: @objc var var_UInt16: UInt16 // CHECK-LABEL: @objc var var_UInt32: UInt32 // CHECK-LABEL: @objc var var_UInt64: UInt64 var var_OpaquePointer: OpaquePointer // CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer var var_PlainClass: PlainClass // CHECK-LABEL: {{^}} var var_PlainClass: PlainClass @objc var var_PlainClass_: PlainClass // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} var var_PlainStruct: PlainStruct // CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct @objc var var_PlainStruct_: PlainStruct // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} var var_PlainEnum: PlainEnum // CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum @objc var var_PlainEnum_: PlainEnum // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}} var var_PlainProtocol: PlainProtocol // CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol @objc var var_PlainProtocol_: PlainProtocol // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}} var var_ClassObjC: Class_ObjC1 // CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1 @objc var var_ClassObjC_: Class_ObjC1 // no-error var var_ProtocolClass: Protocol_Class1 // CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1 @objc var var_ProtocolClass_: Protocol_Class1 // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}} var var_ProtocolObjC: Protocol_ObjC1 // CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1 @objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error var var_PlainClassMetatype: PlainClass.Type // CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type @objc var var_PlainClassMetatype_: PlainClass.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainStructMetatype: PlainStruct.Type // CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type @objc var var_PlainStructMetatype_: PlainStruct.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainEnumMetatype: PlainEnum.Type // CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type @objc var var_PlainEnumMetatype_: PlainEnum.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainExistentialMetatype: PlainProtocol.Type // CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type @objc var var_PlainExistentialMetatype_: PlainProtocol.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ClassObjCMetatype: Class_ObjC1.Type // CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type @objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error var var_ProtocolClassMetatype: Protocol_Class1.Type // CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type @objc var var_ProtocolClassMetatype_: Protocol_Class1.Type // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type // CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type @objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type // CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type @objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error var var_AnyObject1: AnyObject var var_AnyObject2: AnyObject.Type // CHECK-LABEL: @objc var var_AnyObject1: AnyObject // CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type var var_Existential0: protocol<> // CHECK-LABEL: {{^}} var var_Existential0: protocol<> @objc var var_Existential0_: protocol<> // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{'protocol<>' is not considered '@objc'; use 'AnyObject' instead}} var var_Existential1: protocol<PlainProtocol> // CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol @objc var var_Existential1_: protocol<PlainProtocol> // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}} var var_Existential2: protocol<PlainProtocol, PlainProtocol> // CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol @objc var var_Existential2_: protocol<PlainProtocol, PlainProtocol> // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}} var var_Existential3: protocol<PlainProtocol, Protocol_Class1> // CHECK-LABEL: {{^}} var var_Existential3: protocol<PlainProtocol, Protocol_Class1> @objc var var_Existential3_: protocol<PlainProtocol, Protocol_Class1> // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}} var var_Existential4: protocol<PlainProtocol, Protocol_ObjC1> // CHECK-LABEL: {{^}} var var_Existential4: protocol<PlainProtocol, Protocol_ObjC1> @objc var var_Existential4_: protocol<PlainProtocol, Protocol_ObjC1> // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}} var var_Existential5: protocol<Protocol_Class1> // CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1 @objc var var_Existential5_: protocol<Protocol_Class1> // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}} var var_Existential6: protocol<Protocol_Class1, Protocol_Class2> // CHECK-LABEL: {{^}} var var_Existential6: protocol<Protocol_Class1, Protocol_Class2> @objc var var_Existential6_: protocol<Protocol_Class1, Protocol_Class2> // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}} var var_Existential7: protocol<Protocol_Class1, Protocol_ObjC1> // CHECK-LABEL: {{^}} var var_Existential7: protocol<Protocol_Class1, Protocol_ObjC1> @objc var var_Existential7_: protocol<Protocol_Class1, Protocol_ObjC1> // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}} var var_Existential8: protocol<Protocol_ObjC1> // CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1 @objc var var_Existential8_: protocol<Protocol_ObjC1> // no-error var var_Existential9: protocol<Protocol_ObjC1, Protocol_ObjC2> // CHECK-LABEL: @objc var var_Existential9: protocol<Protocol_ObjC1, Protocol_ObjC2> @objc var var_Existential9_: protocol<Protocol_ObjC1, Protocol_ObjC2> // no-error var var_ExistentialMetatype0: protocol<>.Type var var_ExistentialMetatype1: protocol<PlainProtocol>.Type var var_ExistentialMetatype2: protocol<PlainProtocol, PlainProtocol>.Type var var_ExistentialMetatype3: protocol<PlainProtocol, Protocol_Class1>.Type var var_ExistentialMetatype4: protocol<PlainProtocol, Protocol_ObjC1>.Type var var_ExistentialMetatype5: protocol<Protocol_Class1>.Type var var_ExistentialMetatype6: protocol<Protocol_Class1, Protocol_Class2>.Type var var_ExistentialMetatype7: protocol<Protocol_Class1, Protocol_ObjC1>.Type var var_ExistentialMetatype8: protocol<Protocol_ObjC1>.Type var var_ExistentialMetatype9: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype0: protocol<>.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype2: PlainProtocol.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype3: protocol<PlainProtocol, Protocol_Class1>.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype4: protocol<PlainProtocol, Protocol_ObjC1>.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype5: Protocol_Class1.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype6: protocol<Protocol_Class1, Protocol_Class2>.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype7: protocol<Protocol_Class1, Protocol_ObjC1>.Type // CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type // CHECK-LABEL: @objc var var_ExistentialMetatype9: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int> var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool> var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool> var var_UnsafeMutablePointer4: UnsafeMutablePointer<String> var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float> var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double> var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer> var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass> var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct> var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum> var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol> var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject> var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type> var var_UnsafeMutablePointer100: UnsafeMutablePointer<()> var var_UnsafeMutablePointer101: UnsafeMutablePointer<Void> var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)> // CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int> // CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool> // CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String> // CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float> // CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double> // CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol> // CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject> // CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type> // CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutablePointer<()> // CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutablePointer<Void> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)> var var_Optional1: Class_ObjC1? var var_Optional2: Protocol_ObjC1? var var_Optional3: Class_ObjC1.Type? var var_Optional4: Protocol_ObjC1.Type? var var_Optional5: AnyObject? var var_Optional6: AnyObject.Type? var var_Optional7: String? var var_Optional8: protocol<Protocol_ObjC1>? var var_Optional9: protocol<Protocol_ObjC1>.Type? var var_Optional10: protocol<Protocol_ObjC1, Protocol_ObjC2>? var var_Optional11: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type? // CHECK-LABEL: @objc var var_Optional1: Class_ObjC1? // CHECK-LABEL: @objc var var_Optional2: Protocol_ObjC1? // CHECK-LABEL: @objc var var_Optional3: Class_ObjC1.Type? // CHECK-LABEL: @objc var var_Optional4: Protocol_ObjC1.Type? // CHECK-LABEL: @objc var var_Optional5: AnyObject? // CHECK-LABEL: @objc var var_Optional6: AnyObject.Type? // CHECK-LABEL: @objc var var_Optional7: String? // CHECK-LABEL: @objc var var_Optional8: Protocol_ObjC1? // CHECK-LABEL: @objc var var_Optional9: Protocol_ObjC1.Type? // CHECK-LABEL: @objc var var_Optional10: protocol<Protocol_ObjC1, Protocol_ObjC2>? // CHECK-LABEL: @objc var var_Optional11: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type? var var_ImplicitlyUnwrappedOptional1: Class_ObjC1! var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1! var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type! var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type! var var_ImplicitlyUnwrappedOptional5: AnyObject! var var_ImplicitlyUnwrappedOptional6: AnyObject.Type! var var_ImplicitlyUnwrappedOptional7: String! var var_ImplicitlyUnwrappedOptional8: protocol<Protocol_ObjC1>! var var_ImplicitlyUnwrappedOptional9: protocol<Protocol_ObjC1, Protocol_ObjC2>! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional1: Class_ObjC1! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional5: AnyObject! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional6: AnyObject.Type! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional7: String! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1! // CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional9: protocol<Protocol_ObjC1, Protocol_ObjC2>! var var_Optional_fail1: PlainClass? var var_Optional_fail2: PlainClass.Type? var var_Optional_fail3: PlainClass! var var_Optional_fail4: PlainStruct? var var_Optional_fail5: PlainStruct.Type? var var_Optional_fail6: PlainEnum? var var_Optional_fail7: PlainEnum.Type? var var_Optional_fail8: PlainProtocol? var var_Optional_fail9: protocol<>? var var_Optional_fail10: protocol<PlainProtocol>? var var_Optional_fail11: protocol<PlainProtocol, Protocol_ObjC1>? var var_Optional_fail12: Int? var var_Optional_fail13: Bool? var var_Optional_fail14: CBool? var var_Optional_fail16: OpaquePointer? var var_Optional_fail17: UnsafeMutablePointer<Int>? var var_Optional_fail18: UnsafeMutablePointer<Class_ObjC1>? var var_Optional_fail20: AnyObject?? var var_Optional_fail21: AnyObject.Type?? // CHECK-NOT: @objc{{.*}}Optional_fail // CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> () var var_CFunctionPointer_1: @convention(c) () -> () // CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{attribute only applies to syntactic function types}} // CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) PlainStruct -> Int var var_CFunctionPointer_invalid_2: @convention(c) PlainStruct -> Int // expected-error {{'PlainStruct -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}} // <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}} weak var var_Weak1: Class_ObjC1? weak var var_Weak2: Protocol_ObjC1? // <rdar://problem/16473062> weak and unowned variables of metatypes are rejected //weak var var_Weak3: Class_ObjC1.Type? //weak var var_Weak4: Protocol_ObjC1.Type? weak var var_Weak5: AnyObject? //weak var var_Weak6: AnyObject.Type? weak var var_Weak7: protocol<Protocol_ObjC1>? weak var var_Weak8: protocol<Protocol_ObjC1, Protocol_ObjC2>? // CHECK-LABEL: @objc weak var var_Weak1: @sil_weak Class_ObjC1 // CHECK-LABEL: @objc weak var var_Weak2: @sil_weak Protocol_ObjC1 // CHECK-LABEL: @objc weak var var_Weak5: @sil_weak AnyObject // CHECK-LABEL: @objc weak var var_Weak7: @sil_weak Protocol_ObjC1 // CHECK-LABEL: @objc weak var var_Weak8: @sil_weak protocol<Protocol_ObjC1, Protocol_ObjC2> weak var var_Weak_fail1: PlainClass? weak var var_Weak_bad2: PlainStruct? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}} weak var var_Weak_bad3: PlainEnum? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}} weak var var_Weak_bad4: String? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}} // CHECK-NOT: @objc{{.*}}Weak_fail unowned var var_Unowned1: Class_ObjC1 unowned var var_Unowned2: Protocol_ObjC1 // <rdar://problem/16473062> weak and unowned variables of metatypes are rejected //unowned var var_Unowned3: Class_ObjC1.Type //unowned var var_Unowned4: Protocol_ObjC1.Type unowned var var_Unowned5: AnyObject //unowned var var_Unowned6: AnyObject.Type unowned var var_Unowned7: protocol<Protocol_ObjC1> unowned var var_Unowned8: protocol<Protocol_ObjC1, Protocol_ObjC2> // CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject // CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned protocol<Protocol_ObjC1, Protocol_ObjC2> unowned var var_Unowned_fail1: PlainClass unowned var var_Unowned_bad2: PlainStruct // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}} unowned var var_Unowned_bad3: PlainEnum // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}} unowned var var_Unowned_bad4: String // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}} // CHECK-NOT: @objc{{.*}}Unowned_fail var var_FunctionType1: () -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> () var var_FunctionType2: (Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> () var var_FunctionType3: (Int) -> Int // CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int var var_FunctionType4: (Int, Double) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> () var var_FunctionType5: (String) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> () var var_FunctionType6: () -> String // CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String var var_FunctionType7: (PlainClass) -> () // CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> () var var_FunctionType8: () -> PlainClass // CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass var var_FunctionType9: (PlainStruct) -> () // CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> () var var_FunctionType10: () -> PlainStruct // CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct var var_FunctionType11: (PlainEnum) -> () // CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> () var var_FunctionType12: (PlainProtocol) -> () // CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> () var var_FunctionType13: (Class_ObjC1) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> () var var_FunctionType14: (Protocol_Class1) -> () // CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> () var var_FunctionType15: (Protocol_ObjC1) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> () var var_FunctionType16: (AnyObject) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> () var var_FunctionType17: (() -> ()) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> () var var_FunctionType18: ((Int) -> (), Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> () var var_FunctionType19: ((String) -> (), Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> () var var_FunctionTypeReturn1: () -> () -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> () @objc var var_FunctionTypeReturn1_: () -> () -> () // no-error var var_FunctionTypeReturn2: () -> (Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> () @objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error var var_FunctionTypeReturn3: () -> () -> Int // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int @objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error var var_FunctionTypeReturn4: () -> (String) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> () @objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error var var_FunctionTypeReturn5: () -> () -> String // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String @objc var var_FunctionTypeReturn5_: () -> () -> String // no-error var var_BlockFunctionType1: @convention(block) () -> () // CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> () @objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error var var_ArrayType1: [AnyObject] // CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject] @objc var var_ArrayType1_: [AnyObject] // no-error var var_ArrayType2: [@convention(block) AnyObject -> AnyObject] // no-error // CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) AnyObject -> AnyObject] @objc var var_ArrayType2_: [@convention(block) AnyObject -> AnyObject] // no-error var var_ArrayType3: [PlainStruct] // CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct] @objc var var_ArrayType3_: [PlainStruct] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType4: [AnyObject -> AnyObject] // no-error // CHECK-LABEL: {{^}} var var_ArrayType4: [AnyObject -> AnyObject] @objc var var_ArrayType4_: [AnyObject -> AnyObject] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType5: [Protocol_ObjC1] // CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1] @objc var var_ArrayType5_: [Protocol_ObjC1] // no-error var var_ArrayType6: [Class_ObjC1] // CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1] @objc var var_ArrayType6_: [Class_ObjC1] // no-error var var_ArrayType7: [PlainClass] // CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass] @objc var var_ArrayType7_: [PlainClass] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType8: [PlainProtocol] // CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol] @objc var var_ArrayType8_: [PlainProtocol] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType9: [protocol<Protocol_ObjC1, PlainProtocol>] // CHECK-LABEL: {{^}} var var_ArrayType9: [protocol<{{.+}}>] @objc var var_ArrayType9_: [protocol<Protocol_ObjC1, PlainProtocol>] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType10: [protocol<Protocol_ObjC1, Protocol_ObjC2>] // CHECK-LABEL: {{^}} @objc var var_ArrayType10: [protocol<{{.+}}>] @objc var var_ArrayType10_: [protocol<Protocol_ObjC1, Protocol_ObjC2>] // no-error var var_ArrayType11: [Any] // CHECK-LABEL: {{^}} var var_ArrayType11: [Any] @objc var var_ArrayType11_: [Any] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType12: [Any!] // CHECK-LABEL: {{^}} var var_ArrayType12: [Any!] @objc var var_ArrayType12_: [Any!] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType13: [Any?] // CHECK-LABEL: {{^}} var var_ArrayType13: [Any?] @objc var var_ArrayType13_: [Any?] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType14: [AnyObject!] // CHECK-LABEL: {{^}} var var_ArrayType14: [AnyObject!] @objc var var_ArrayType14_: [AnyObject!] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType15: [AnyObject?] // CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?] @objc var var_ArrayType15_: [AnyObject?] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType16: [[@convention(block) AnyObject -> AnyObject]] // no-error // CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) AnyObject -> AnyObject]] @objc var var_ArrayType16_: [[@convention(block) AnyObject -> AnyObject]] // no-error var var_ArrayType17: [[AnyObject -> AnyObject]] // no-error // CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[AnyObject -> AnyObject]] @objc var var_ArrayType17_: [[AnyObject -> AnyObject]] // expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} } @objc class ObjCBase {} class infer_instanceVar2< GP_Unconstrained, GP_PlainClass : PlainClass, GP_PlainProtocol : PlainProtocol, GP_Class_ObjC : Class_ObjC1, GP_Protocol_Class : Protocol_Class1, GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase { // CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase { override init() {} var var_GP_Unconstrained: GP_Unconstrained // CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained @objc var var_GP_Unconstrained_: GP_Unconstrained // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_PlainClass: GP_PlainClass // CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass @objc var var_GP_PlainClass_: GP_PlainClass // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_PlainProtocol: GP_PlainProtocol // CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol @objc var var_GP_PlainProtocol_: GP_PlainProtocol // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Class_ObjC: GP_Class_ObjC // CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC @objc var var_GP_Class_ObjC_: GP_Class_ObjC // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Protocol_Class: GP_Protocol_Class // CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class @objc var var_GP_Protocol_Class_: GP_Protocol_Class // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC // CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC @objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC // expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} func func_GP_Unconstrained(a: GP_Unconstrained) {} // CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) { @objc func func_GP_Unconstrained_(a: GP_Unconstrained) {} // expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} } class infer_instanceVar3 : Class_ObjC1 { // CHECK-LABEL: @objc class infer_instanceVar3 : Class_ObjC1 { var v1: Int = 0 // CHECK-LABEL: @objc var v1: Int } @objc protocol infer_instanceVar4 { // CHECK-LABEL: @objc protocol infer_instanceVar4 { var v1: Int { get } // CHECK-LABEL: @objc var v1: Int { get } } // @!objc class infer_instanceVar5 { // CHECK-LABEL: {{^}}class infer_instanceVar5 { @objc var intstanceVar1: Int { // CHECK: @objc var intstanceVar1: Int get {} // CHECK: @objc get {} set {} // CHECK: @objc set {} } } @objc class infer_staticVar1 { // CHECK-LABEL: @objc class infer_staticVar1 { class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}} // CHECK: @objc class var staticVar1: Int } // @!objc class infer_subscript1 { // CHECK-LABEL: class infer_subscript1 @objc subscript(i: Int) -> Int { // CHECK: @objc subscript(i: Int) -> Int get {} // CHECK: @objc get {} set {} // CHECK: @objc set {} } } @objc protocol infer_throughConformanceProto1 { // CHECK-LABEL: @objc protocol infer_throughConformanceProto1 { func funcObjC1() var varObjC1: Int { get } var varObjC2: Int { get set } // CHECK: @objc func funcObjC1() // CHECK: @objc var varObjC1: Int { get } // CHECK: @objc var varObjC2: Int { get set } } class infer_class1 : PlainClass {} // CHECK-LABEL: {{^}}class infer_class1 : PlainClass { class infer_class2 : Class_ObjC1 {} // CHECK-LABEL: @objc class infer_class2 : Class_ObjC1 { class infer_class3 : infer_class2 {} // CHECK-LABEL: @objc class infer_class3 : infer_class2 { class infer_class4 : Protocol_Class1 {} // CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 { class infer_class5 : Protocol_ObjC1 {} // CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 { // // If a protocol conforms to an @objc protocol, this does not infer @objc on // the protocol itself, or on the newly introduced requirements. Only the // inherited @objc requirements get @objc. // // Same rule applies to classes. // protocol infer_protocol1 { // CHECK-LABEL: {{^}}protocol infer_protocol1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol2 : Protocol_Class1 { // CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol3 : Protocol_ObjC1 { // CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 { // CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 { // CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } class C { // Don't crash. @objc func foo(x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}} @IBAction func myAction(sender: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}} } //===--- //===--- @IBOutlet implies @objc //===--- class HasIBOutlet { // CHECK-LABEL: {{^}}class HasIBOutlet { init() {} @IBOutlet weak var goodOutlet: Class_ObjC1! // CHECK-LABEL: {{^}} @IBOutlet @objc weak var goodOutlet: @sil_weak Class_ObjC1! @IBOutlet var badOutlet: PlainStruct // expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}} // CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct } //===--- //===--- @NSManaged implies @objc //===--- class HasNSManaged { // CHECK-LABEL: {{^}}class HasNSManaged { init() {} @NSManaged var goodManaged: Class_ObjC1 // CHECK-LABEL: {{^}} @NSManaged @objc dynamic var goodManaged: Class_ObjC1 @NSManaged var badManaged: PlainStruct // expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // CHECK-LABEL: {{^}} @NSManaged var badManaged: PlainStruct } //===--- //===--- Pointer argument types //===--- @objc class TakesCPointers { // CHECK-LABEL: {{^}}@objc class TakesCPointers { func constUnsafeMutablePointer(p: UnsafePointer<Int>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) { func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) { func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) { func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {} // CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) { func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {} // CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) { func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {} // CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) { } // @objc with nullary names @objc(NSObjC2) class Class_ObjC2 { // CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2 @objc(initWithMalice) init(foo: ()) { } @objc(initWithIntent) init(bar _: ()) { } @objc(initForMurder) init() { } @objc(isFoo) func foo() -> Bool {} // CHECK-LABEL: @objc(isFoo) func foo() -> Bool { } @objc() // expected-error{{expected name within parentheses of @objc attribute}} class Class_ObjC3 { } // @objc with selector names extension PlainClass { // CHECK-LABEL: @objc(setFoo:) dynamic func @objc(setFoo:) func foo(b: Bool) { } // CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set @objc(setWithRed:green:blue:alpha:) func set(_: Float, green: Float, blue: Float, alpha: Float) { } // CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith @objc(createWithRed:green blue:alpha) class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { } // expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}} // expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}} // CHECK-LABEL: @objc(::) dynamic func badlyNamed @objc(::) func badlyNamed(_: Int, y: Int) {} } @objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}} class BadClass1 { } @objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}} protocol BadProto1 { } @objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}} enum BadEnum1: Int { case X } @objc enum BadEnum2: Int { @objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}} case X } class BadClass2 { @objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}} var badprop: Int = 5 @objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}} subscript (i: Int) -> Int { get { return i } } @objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}} func noArgNamesOneParam(x: Int) { } @objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}} func noArgNamesOneParam2(_: Int) { } @objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}} func noArgNamesTwoParams(_: Int, y: Int) { } @objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}} func oneArgNameTwoParams(_: Int, y: Int) { } @objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}} func oneArgNameNoParams() { } @objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}} init() { } var _prop = 5 @objc var prop: Int { @objc(property) get { return _prop } @objc(setProperty:) set { _prop = newValue } } var prop2: Int { @objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}} @objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}} } var prop3: Int { @objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-10=}} } @objc subscript (c: Class_ObjC1) -> Class_ObjC1 { @objc(getAtClass:) get { return c } @objc(setAtClass:class:) set { } } } // Swift overrides that aren't also @objc overrides. class Super { @objc(renamedFoo) var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}} @objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process' here}} } class Sub1 : Super { @objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}} override var foo: Int { get { return 5 } } override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}} } class Sub2 : Super { @objc override var foo: Int { get { return 5 } } } class Sub3 : Super { override var foo: Int { get { return 5 } } } class Sub4 : Super { @objc(renamedFoo) override var foo: Int { get { return 5 } } } class Sub5 : Super { @objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}} override var foo: Int { get { return 5 } } } enum NotObjCEnum { case X } struct NotObjCStruct {} // Closure arguments can only be @objc if their parameters and returns are. // CHECK-LABEL: @objc class ClosureArguments @objc class ClosureArguments { // CHECK: @objc func foo @objc func foo(f: Int -> ()) {} // CHECK: @objc func bar @objc func bar(f: NotObjCEnum -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func bas @objc func bas(f: NotObjCEnum -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func zim @objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func zang @objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} @objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func fooImplicit func fooImplicit(f: Int -> ()) {} // CHECK: {{^}} func barImplicit func barImplicit(f: NotObjCEnum -> NotObjCStruct) {} // CHECK: {{^}} func basImplicit func basImplicit(f: NotObjCEnum -> ()) {} // CHECK: {{^}} func zimImplicit func zimImplicit(f: () -> NotObjCStruct) {} // CHECK: {{^}} func zangImplicit func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // CHECK: {{^}} func zangZangImplicit func zangZangImplicit(f: (Int...) -> ()) {} } typealias GoodBlock = @convention(block) Int -> () typealias BadBlock = @convention(block) NotObjCEnum -> () // expected-error{{'NotObjCEnum -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}} @objc class AccessControl { // CHECK: @objc func foo func foo() {} // CHECK: {{^}} private func bar private func bar() {} // CHECK: @objc private func baz @objc private func baz() {} } //===--- Ban @objc +load methods class Load1 { // Okay: not @objc class func load() { } class func alloc() {} class func allocWithZone(_: Int) {} } @objc class Load2 { class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}} class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}} class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}} } @objc class Load3 { class var load: Load3 { get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}} set { } } @objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}} @objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}} } // Members of protocol extensions cannot be @objc extension PlainProtocol { @objc final var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc final subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc final func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} } extension Protocol_ObjC1 { @objc final var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc final subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} @objc final func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} } extension Protocol_ObjC1 { // Don't infer @objc for extensions of @objc protocols. // CHECK: {{^}} var propertyOK: Int final var propertyOK: Int { return 5 } } //===--- //===--- Error handling //===--- class ClassThrows1 { // CHECK: @objc func methodReturnsVoid() throws @objc func methodReturnsVoid() throws { } // CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1 @objc func methodReturnsObjCClass() throws -> Class_ObjC1 { return Class_ObjC1() } // CHECK: @objc func methodReturnsBridged() throws -> String @objc func methodReturnsBridged() throws -> String { return String() } // CHECK: @objc func methodReturnsArray() throws -> [String] @objc func methodReturnsArray() throws -> [String] { return [String]() } // CHECK: @objc init(degrees: Double) throws @objc init(degrees: Double) throws { } // Errors @objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}} @objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}} @objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}} @objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { } // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{throwing function types cannot be represented in Objective-C}} @objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}} @objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}} } // CHECK-DUMP-LABEL: class_decl "ImplicitClassThrows1" @objc class ImplicitClassThrows1 { // CHECK: @objc func methodReturnsVoid() throws // CHECK-DUMP: func_decl "methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>>,resulttype=Bool func methodReturnsVoid() throws { } // CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1 // CHECK-DUMP: func_decl "methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>> func methodReturnsObjCClass() throws -> Class_ObjC1 { return Class_ObjC1() } // CHECK: @objc func methodReturnsBridged() throws -> String func methodReturnsBridged() throws -> String { return String() } // CHECK: @objc func methodReturnsArray() throws -> [String] func methodReturnsArray() throws -> [String] { return [String]() } // CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // CHECK: @objc func methodWithTrailingClosures(s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int, fn3: (Int) -> Int) // CHECK-DUMP: func_decl "methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>>,resulttype=Bool func methodWithTrailingClosures(s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int, fn3: (Int) -> Int) throws { } // CHECK: @objc init(degrees: Double) throws // CHECK-DUMP: constructor_decl "init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>> init(degrees: Double) throws { } } // CHECK-DUMP-LABEL: class_decl "SubclassImplicitClassThrows1" @objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 { // CHECK: @objc override func methodWithTrailingClosures(s: String, fn1: ((Int) -> Int), fn2: ((Int) -> Int), fn3: ((Int) -> Int)) // CHECK-DUMP: func_decl "methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>>,resulttype=Bool override func methodWithTrailingClosures(s: String, fn1: ((Int) -> Int), fn2: ((Int) -> Int), fn3: ((Int) -> Int)) throws { } } class ThrowsRedecl1 { @objc func method1(x: Int, error: Class_ObjC1) { } // expected-note{{declared here}} @objc func method1(x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}} @objc func method2AndReturnError(x: Int) { } // expected-note{{declared here}} @objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}} @objc func method3(x: Int, error: Int, closure: Int -> Int) { } // expected-note{{declared here}} @objc func method3(x: Int, closure: Int -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}} @objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}} @objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}} @objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}} @objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}} @objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: Int -> Int) { } // expected-note{{declared here}} @objc init(fn: Int -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}} } class ThrowsObjCName { @objc(method4:closure:error:) func method4(x: Int, closure: Int -> Int) throws { } @objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: Int -> Int) throws { } @objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}} @objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}} // CHECK-DUMP: func_decl "method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>>,resulttype=Bool @objc(method8:fn1:error:fn2:) func method8(s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int) throws { } // CHECK-DUMP: func_decl "method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>>,resulttype=Bool @objc(method9AndReturnError:s:fn1:fn2:) func method9(s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int) throws { } } class SubclassThrowsObjCName : ThrowsObjCName { // CHECK-DUMP: func_decl "method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>>,resulttype=Bool override func method8(s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int) throws { } // CHECK-DUMP: func_decl "method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=AutoreleasingUnsafeMutablePointer<Optional<NSError>>,resulttype=Bool override func method9(s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int) throws { } } @objc protocol ProtocolThrowsObjCName { optional func doThing(x: String) throws -> String // expected-note{{requirement 'doThing' declared here}} } class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName { @objc func doThing(x: String) throws -> String { return x } // okay } class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName { // expected-note{{class 'ConformsToProtocolThrowsObjCName2' declares conformance to protocol 'ProtocolThrowsObjCName' here}} @objc func doThing(x: Int) throws -> String { return "" } // expected-error{{Objective-C method 'doThing:error:' provided by method 'doThing' conflicts with optional requirement method 'doThing' in protocol 'ProtocolThrowsObjCName'}} } @objc class DictionaryTest { // CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { } // CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { } func func_dictionary2a(x: Dictionary<String, Int>) { } @objc func func_dictionary2b(x: Dictionary<String, Int>) { } } @objc class ObjC_Class1 : Hashable { var hashValue: Int { return 0 } } func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool { return true }
e119bdd144f450b10540797d619d4f87
39.471707
293
0.70105
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
Gesture/TouchExplorer/TouchExplorer/ViewController.swift
mit
1
// // ViewController.swift // TouchExplorer // // Created by Domenico on 01/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var messageLabel:UILabel! @IBOutlet var tapsLabel:UILabel! @IBOutlet var touchesLabel:UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func updateLabelsFromTouches(_ touches:Set<NSObject>!) { let touch = touches.first as! UITouch let numTaps = touch.tapCount let tapsMessage = "\(numTaps) taps detected" tapsLabel.text = tapsMessage let numTouches = touches.count let touchMsg = "\(numTouches) touches detected" touchesLabel.text = touchMsg } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { messageLabel.text = "Touches Began" updateLabelsFromTouches(event?.allTouches) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { messageLabel.text = "Touches Cancelled" updateLabelsFromTouches(event?.allTouches) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { messageLabel.text = "Touches Ended" updateLabelsFromTouches(event?.allTouches) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { messageLabel.text = "Drag Detected" updateLabelsFromTouches(event?.allTouches) } }
74a728c7a25be05c1658fcf9a961233f
28.796296
83
0.660659
false
false
false
false
Brightify/ReactantUI
refs/heads/master
Sources/Tokenizer/Layout/LayoutAnchor.swift
mit
1
// // LayoutAnchor.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation public enum LayoutAnchor: CustomStringConvertible { case top case bottom case leading case trailing case left case right case width case height case centerX case centerY case firstBaseline case lastBaseline case size public var description: String { switch self { case .top: return "top" case .bottom: return "bottom" case .leading: return "leading" case .trailing: return "trailing" case .left: return "left" case .right: return "right" case .width: return "width" case .height: return "height" case .centerX: return "centerX" case .centerY: return "centerY" case .firstBaseline: return "firstBaseline" case .lastBaseline: return "lastBaseline" case .size: return "size" } } init(_ string: String) throws { switch string { case "leading": self = .leading case "trailing": self = .trailing case "left": self = .left case "right": self = .right case "top": self = .top case "bottom": self = .bottom case "width": self = .width case "height": self = .height case "centerX": self = .centerX case "centerY": self = .centerY case "firstBaseline": self = .firstBaseline case "lastBaseline": self = .lastBaseline case "size": self = .size default: throw TokenizationError(message: "Unknown layout anchor \(string)") } } }
f6fd810412134d7e1834e4730713cf13
21.52809
79
0.497756
false
false
false
false
apple/swift-tools-support-core
refs/heads/main
Sources/TSCUtility/ArgumentParser.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import TSCBasic import Foundation import func TSCLibc.exit /// Errors which may be encountered when running argument parser. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public enum ArgumentParserError: Swift.Error { /// An unknown option is encountered. case unknownOption(String, suggestion: String?) /// The value of an argument is invalid. case invalidValue(argument: String, error: ArgumentConversionError) /// Expected a value from the option. case expectedValue(option: String) /// An unexpected positional argument encountered. case unexpectedArgument(String) /// Expected these positional arguments but not found. case expectedArguments(ArgumentParser, [String]) /// Expected a single argument but got multiple ones. case duplicateArgument(String) } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension ArgumentParserError: LocalizedError { public var errorDescription: String? { return description } } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension ArgumentParserError: CustomStringConvertible { public var description: String { switch self { case .unknownOption(let option, let suggestion): var desc = "unknown option \(option); use --help to list available options" if let suggestion = suggestion { desc += "\nDid you mean \(suggestion)?" } return desc case .invalidValue(let argument, let error): return "\(error) for argument \(argument); use --help to print usage" case .expectedValue(let option): return "option \(option) requires a value; provide a value using '\(option) <value>' or '\(option)=<value>'" case .unexpectedArgument(let argument): return "unexpected argument \(argument); use --help to list available arguments" case .expectedArguments(_, let arguments): return "expected arguments: \(arguments.joined(separator: ", "))" case .duplicateArgument(let option): return "expected single value for argument: \(option)" } } } /// Conversion errors that can be returned from `ArgumentKind`'s failable /// initializer. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public enum ArgumentConversionError: Swift.Error { /// The value is unknown. case unknown(value: String) /// The value could not be converted to the target type. case typeMismatch(value: String, expectedType: Any.Type) /// Custom reason for conversion failure. case custom(String) } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension ArgumentConversionError: LocalizedError { public var errorDescription: String? { return description } } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension ArgumentConversionError: CustomStringConvertible { public var description: String { switch self { case .unknown(let value): return "unknown value '\(value)'" case .typeMismatch(let value, let expectedType): return "'\(value)' is not convertible to \(expectedType)" case .custom(let reason): return reason } } } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension ArgumentConversionError: Equatable { public static func ==(lhs: ArgumentConversionError, rhs: ArgumentConversionError) -> Bool { switch (lhs, rhs) { case (.unknown(let lhsValue), .unknown(let rhsValue)): return lhsValue == rhsValue case (.unknown, _): return false case (.typeMismatch(let lhsValue, let lhsType), .typeMismatch(let rhsValue, let rhsType)): return lhsValue == rhsValue && lhsType == rhsType case (.typeMismatch, _): return false case (.custom(let lhsReason), .custom(let rhsReason)): return lhsReason == rhsReason case (.custom, _): return false } } } /// Different shells for which we can generate shell scripts. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public enum Shell: String, StringEnumArgument { case bash case zsh public static var completion: ShellCompletion = .values([ (bash.rawValue, "generate completion script for Bourne-again shell"), (zsh.rawValue, "generate completion script for Z shell"), ]) } /// Various shell completions modes supplied by ArgumentKind. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public enum ShellCompletion { /// Offers no completions at all. /// /// e.g. for a string identifier. case none /// No specific completions. /// /// The tool will provide its own completions. case unspecified /// Offers filename completions. case filename /// Custom function for generating completions. /// /// Must be provided in the script's scope. case function(String) /// Offers completions from a predefined list. /// /// A description can be provided which is shown in some shells, like zsh. case values([(value: String, description: String)]) } /// A protocol representing the possible types of arguments. /// /// Conforming to this protocol will qualify the type to act as /// positional and option arguments in the argument parser. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public protocol ArgumentKind { /// Throwable convertion initializer. init(argument: String) throws /// Type of shell completion to provide for this argument. static var completion: ShellCompletion { get } } // MARK: - ArgumentKind conformance for common types // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension String: ArgumentKind { public init(argument: String) throws { self = argument } public static let completion: ShellCompletion = .none } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension Int: ArgumentKind { public init(argument: String) throws { guard let int = Int(argument) else { throw ArgumentConversionError.typeMismatch(value: argument, expectedType: Int.self) } self = int } public static let completion: ShellCompletion = .none } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension Bool: ArgumentKind { public init(argument: String) throws { guard let bool = Bool(argument) else { throw ArgumentConversionError.unknown(value: argument) } self = bool } public static var completion: ShellCompletion = .unspecified } /// A protocol which implements ArgumentKind for string initializable enums. /// /// Conforming to this protocol will automatically make an enum with is /// String initializable conform to ArgumentKind. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public protocol StringEnumArgument: ArgumentKind { init?(rawValue: String) } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension StringEnumArgument { public init(argument: String) throws { guard let value = Self.init(rawValue: argument) else { throw ArgumentConversionError.unknown(value: argument) } self = value } } /// An argument representing a path (file / directory). /// /// The path is resolved in the current working directory. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public struct PathArgument: ArgumentKind { public let path: AbsolutePath public init(argument: String) throws { // FIXME: This should check for invalid paths. if let cwd = localFileSystem.currentWorkingDirectory { path = try AbsolutePath(validating: argument, relativeTo: cwd) } else { path = try AbsolutePath(validating: argument) } } public static var completion: ShellCompletion = .filename } /// An enum representing the strategy to parse argument values. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public enum ArrayParsingStrategy { /// Will parse only the next argument and append all values together: `-Xcc -Lfoo -Xcc -Lbar`. case oneByOne /// Will parse all values up to the next option argument: `--files file1 file2 --verbosity 1`. case upToNextOption /// Will parse all remaining arguments, usually for executable commands: `swift run exe --option 1`. case remaining /// Function that parses the current arguments iterator based on the strategy /// and returns the parsed values. func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { var values: [ArgumentKind] = [] switch self { case .oneByOne: guard let nextArgument = parser.next() else { throw ArgumentParserError.expectedValue(option: parser.currentArgument) } try values.append(kind.init(argument: nextArgument)) case .upToNextOption: /// Iterate over arguments until the end or an optional argument while let nextArgument = parser.peek(), isPositional(argument: nextArgument) { /// We need to call next to consume the argument. The peek above did not. _ = parser.next() try values.append(kind.init(argument: nextArgument)) } case .remaining: while let nextArgument = parser.next() { try values.append(kind.init(argument: nextArgument)) } } return values } } /// A protocol representing positional or options argument. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") protocol ArgumentProtocol: Hashable { // FIXME: This should be constrained to ArgumentKind but Array can't conform // to it: `extension of type 'Array' with constraints cannot have an // inheritance clause`. // /// The argument kind of this argument for eg String, Bool etc. associatedtype ArgumentKindTy /// Name of the argument which will be parsed by the parser. var name: String { get } /// Short name of the argument, this is usually used in options arguments /// for a short names for e.g: `--help` -> `-h`. var shortName: String? { get } /// The parsing strategy to adopt when parsing values. var strategy: ArrayParsingStrategy { get } /// Defines is the argument is optional var isOptional: Bool { get } /// The usage text associated with this argument. Used to generate complete help string. var usage: String? { get } /// The shell completions to offer as values for this argument. var completion: ShellCompletion { get } // FIXME: Because `ArgumentKindTy`` can't conform to `ArgumentKind`, this // function has to be provided a kind (which will be different from // ArgumentKindTy for arrays). Once the generics feature exists we can // improve this API. // /// Parses and returns the argument values from the parser. func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] } // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") extension ArgumentProtocol { // MARK: - Conformance for Hashable public func hash(into hasher: inout Hasher) { return hasher.combine(name) } public static func == (_ lhs: Self, _ rhs: Self) -> Bool { return lhs.name == rhs.name && lhs.usage == rhs.usage } } /// Returns true if the given argument does not starts with '-' i.e. it is /// a positional argument, otherwise it is an options argument. fileprivate func isPositional(argument: String) -> Bool { return !argument.hasPrefix("-") } /// A class representing option arguments. These are optional arguments which may /// or may not be provided in the command line. They are always prefixed by their /// name. For e.g. --verbosity true. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public final class OptionArgument<Kind>: ArgumentProtocol { typealias ArgumentKindTy = Kind let name: String let shortName: String? // Option arguments are always optional. var isOptional: Bool { return true } let strategy: ArrayParsingStrategy let usage: String? let completion: ShellCompletion init(name: String, shortName: String?, strategy: ArrayParsingStrategy, usage: String?, completion: ShellCompletion) { precondition(!isPositional(argument: name)) self.name = name self.shortName = shortName self.strategy = strategy self.usage = usage self.completion = completion } func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { do { return try _parse(kind, with: &parser) } catch let conversionError as ArgumentConversionError { throw ArgumentParserError.invalidValue(argument: name, error: conversionError) } } func _parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { // When we have an associated value, we ignore the strategy and only // parse that value. if let associatedArgument = parser.associatedArgumentValue { return try [kind.init(argument: associatedArgument)] } // As a special case, Bool options don't consume arguments. if kind == Bool.self && strategy == .oneByOne { return [true] } let values = try strategy.parse(kind, with: &parser) guard !values.isEmpty else { throw ArgumentParserError.expectedValue(option: name) } return values } } /// A class representing positional arguments. These arguments must be present /// and in the same order as they are added in the parser. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public final class PositionalArgument<Kind>: ArgumentProtocol { typealias ArgumentKindTy = Kind let name: String // Postional arguments don't need short names. var shortName: String? { return nil } let strategy: ArrayParsingStrategy let isOptional: Bool let usage: String? let completion: ShellCompletion init(name: String, strategy: ArrayParsingStrategy, optional: Bool, usage: String?, completion: ShellCompletion) { precondition(isPositional(argument: name)) self.name = name self.strategy = strategy self.isOptional = optional self.usage = usage self.completion = completion } func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { do { return try _parse(kind, with: &parser) } catch let conversionError as ArgumentConversionError { throw ArgumentParserError.invalidValue(argument: name, error: conversionError) } } func _parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { let value = try kind.init(argument: parser.currentArgument) var values = [value] switch strategy { case .oneByOne: // We shouldn't apply the strategy with `.oneByOne` because we // already have one, the parsed `parser.currentArgument`. break case .upToNextOption, .remaining: try values.append(contentsOf: strategy.parse(kind, with: &parser)) } return values } } /// A type-erased argument. /// /// Note: Only used for argument parsing purpose. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") final class AnyArgument: ArgumentProtocol, CustomStringConvertible { typealias ArgumentKindTy = Any let name: String let shortName: String? let strategy: ArrayParsingStrategy let isOptional: Bool let usage: String? let completion: ShellCompletion /// The argument kind this holds, used while initializing that argument. let kind: ArgumentKind.Type /// True if the argument kind is of array type. let isArray: Bool /// A type-erased wrapper around the argument's `parse` function. private let parseClosure: (ArgumentKind.Type, inout ArgumentParserProtocol) throws -> [ArgumentKind] init<T: ArgumentProtocol>(_ argument: T) { self.kind = T.ArgumentKindTy.self as! ArgumentKind.Type self.name = argument.name self.shortName = argument.shortName self.strategy = argument.strategy self.isOptional = argument.isOptional self.usage = argument.usage self.completion = argument.completion self.parseClosure = argument.parse(_:with:) isArray = false } /// Initializer for array arguments. init<T: ArgumentProtocol>(_ argument: T) where T.ArgumentKindTy: Sequence { self.kind = T.ArgumentKindTy.Element.self as! ArgumentKind.Type self.name = argument.name self.shortName = argument.shortName self.strategy = argument.strategy self.isOptional = argument.isOptional self.usage = argument.usage self.completion = argument.completion self.parseClosure = argument.parse(_:with:) isArray = true } var description: String { return "Argument(\(name))" } func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { return try self.parseClosure(kind, &parser) } func parse(with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { return try self.parseClosure(self.kind, &parser) } } // FIXME: We probably don't need this protocol anymore and should convert this to a class. // /// Argument parser protocol passed in initializers of ArgumentKind to manipulate /// parser as needed by the argument. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public protocol ArgumentParserProtocol { /// The current argument being parsed. var currentArgument: String { get } /// The associated value in a `--foo=bar` style argument. var associatedArgumentValue: String? { get } /// Provides (consumes) and returns the next argument. Returns `nil` if there are not arguments left. mutating func next() -> String? /// Peek at the next argument without consuming it. func peek() -> String? } /// Argument parser struct responsible to parse the provided array of arguments /// and return the parsed result. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public final class ArgumentParser { /// A class representing result of the parsed arguments. public class Result: CustomStringConvertible { /// Internal representation of arguments mapped to their values. private var results = [String: Any]() /// Result of the parent parent parser, if any. private var parentResult: Result? /// Reference to the parser this result belongs to. private let parser: ArgumentParser /// The subparser command chosen. fileprivate var subparser: String? /// Create a result with a parser and parent result. init(parser: ArgumentParser, parent: Result?) { self.parser = parser self.parentResult = parent } /// Adds a result. /// /// - Parameters: /// - values: The associated values of the argument. /// - argument: The argument for which this result is being added. /// - Note: /// While it may seem more fragile to use an array as input in the /// case of single-value arguments, this design choice allows major /// simplifications in the parsing code. fileprivate func add(_ values: [ArgumentKind], for argument: AnyArgument) throws { if argument.isArray { var array = results[argument.name] as? [ArgumentKind] ?? [] array.append(contentsOf: values) results[argument.name] = array } else { // We expect only one value for non-array arguments. guard let value = values.spm_only else { assertionFailure() return } guard results[argument.name] == nil else { throw ArgumentParserError.duplicateArgument(argument.name) } results[argument.name] = value } } /// Get an option argument's value from the results. /// /// Since the options are optional, their result may or may not be present. public func get<T>(_ argument: OptionArgument<T>) -> T? { return (results[argument.name] as? T) ?? parentResult?.get(argument) } /// Array variant for option argument's get(_:). public func get<T>(_ argument: OptionArgument<[T]>) -> [T]? { return (results[argument.name] as? [T]) ?? parentResult?.get(argument) } /// Get a positional argument's value. public func get<T>(_ argument: PositionalArgument<T>) -> T? { return results[argument.name] as? T } /// Array variant for positional argument's get(_:). public func get<T>(_ argument: PositionalArgument<[T]>) -> [T]? { return results[argument.name] as? [T] } /// Get an argument's value using its name. /// - throws: An ArgumentParserError.invalidValue error if the parsed argument does not match the expected type. public func get<T>(_ name: String) throws -> T? { guard let value = results[name] else { // if we have a parent and this is an option argument, look in the parent result if let parentResult = parentResult, name.hasPrefix("-") { return try parentResult.get(name) } else { return nil } } guard let typedValue = value as? T else { throw ArgumentParserError.invalidValue(argument: name, error: .typeMismatch(value: String(describing: value), expectedType: T.self)) } return typedValue } /// Returns true if the given arg is present in the results. public func exists(arg: String) -> Bool { return results[arg] != nil } /// Get the subparser which was chosen for the given parser. public func subparser(_ parser: ArgumentParser) -> String? { if parser === self.parser { return subparser } return parentResult?.subparser(parser) } public var description: String { var description = "ArgParseResult(\(results))" if let parent = parentResult { description += " -> " + parent.description } return description } } /// The mapping of subparsers to their subcommand. private(set) var subparsers: [String: ArgumentParser] = [:] /// List of arguments added to this parser. private(set) var optionArguments: [AnyArgument] = [] private(set) var positionalArguments: [AnyArgument] = [] // If provided, will be substituted instead of arg0 in usage text. let commandName: String? /// Usage string of this parser. let usage: String /// Overview text of this parser. let overview: String /// See more text of this parser. let seeAlso: String? /// If this parser is a subparser. private let isSubparser: Bool /// Boolean specifying if the parser can accept further positional /// arguments (false if it already has a positional argument with /// `isOptional` set to `true` or strategy set to `.remaining`). private var canAcceptPositionalArguments: Bool = true /// Create an argument parser. /// /// - Parameters: /// - commandName: If provided, this will be substitued in "usage" line of the generated usage text. /// Otherwise, first command line argument will be used. /// - usage: The "usage" line of the generated usage text. /// - overview: The "overview" line of the generated usage text. /// - seeAlso: The "see also" line of generated usage text. public init(commandName: String? = nil, usage: String, overview: String, seeAlso: String? = nil) { self.isSubparser = false self.commandName = commandName self.usage = usage self.overview = overview self.seeAlso = seeAlso } /// Create a subparser with its help text. private init(subparser commandName: String, usage: String, overview: String) { self.isSubparser = true self.commandName = commandName self.usage = usage self.overview = overview self.seeAlso = nil } /// Adds an option to the parser. public func add<T: ArgumentKind>( option: String, shortName: String? = nil, kind: T.Type = T.self, usage: String? = nil, completion: ShellCompletion? = nil ) -> OptionArgument<T> { assert(!optionArguments.contains(where: { $0.name == option }), "Can not define an option twice") let argument = OptionArgument<T>(name: option, shortName: shortName, strategy: .oneByOne, usage: usage, completion: completion ?? T.completion) optionArguments.append(AnyArgument(argument)) return argument } /// Adds an array argument type. public func add<T: ArgumentKind>( option: String, shortName: String? = nil, kind: [T].Type = [T].self, strategy: ArrayParsingStrategy = .upToNextOption, usage: String? = nil, completion: ShellCompletion? = nil ) -> OptionArgument<[T]> { assert(!optionArguments.contains(where: { $0.name == option }), "Can not define an option twice") let argument = OptionArgument<[T]>(name: option, shortName: shortName, strategy: strategy, usage: usage, completion: completion ?? T.completion) optionArguments.append(AnyArgument(argument)) return argument } /// Adds an argument to the parser. /// /// Note: Only one positional argument is allowed if optional setting is enabled. public func add<T: ArgumentKind>( positional: String, kind: T.Type = T.self, optional: Bool = false, usage: String? = nil, completion: ShellCompletion? = nil ) -> PositionalArgument<T> { precondition(subparsers.isEmpty, "Positional arguments are not supported with subparsers") precondition(canAcceptPositionalArguments, "Can not accept more positional arguments") if optional { canAcceptPositionalArguments = false } let argument = PositionalArgument<T>(name: positional, strategy: .oneByOne, optional: optional, usage: usage, completion: completion ?? T.completion) positionalArguments.append(AnyArgument(argument)) return argument } /// Adds an argument to the parser. /// /// Note: Only one multiple-value positional argument is allowed. public func add<T: ArgumentKind>( positional: String, kind: [T].Type = [T].self, optional: Bool = false, strategy: ArrayParsingStrategy = .upToNextOption, usage: String? = nil, completion: ShellCompletion? = nil ) -> PositionalArgument<[T]> { precondition(subparsers.isEmpty, "Positional arguments are not supported with subparsers") precondition(canAcceptPositionalArguments, "Can not accept more positional arguments") if optional || strategy == .remaining { canAcceptPositionalArguments = false } let argument = PositionalArgument<[T]>(name: positional, strategy: strategy, optional: optional, usage: usage, completion: completion ?? T.completion) positionalArguments.append(AnyArgument(argument)) return argument } /// Add a parser with a subcommand name and its corresponding overview. @discardableResult public func add(subparser command: String, usage: String = "", overview: String) -> ArgumentParser { precondition(positionalArguments.isEmpty, "Subparsers are not supported with positional arguments") let parser = ArgumentParser(subparser: command, usage: usage, overview: overview) subparsers[command] = parser return parser } // MARK: - Parsing /// A wrapper struct to pass to the ArgumentKind initializers. struct Parser: ArgumentParserProtocol { let currentArgument: String private(set) var associatedArgumentValue: String? /// The iterator used to iterate arguments. fileprivate var argumentsIterator: IndexingIterator<[String]> init(associatedArgumentValue: String?, argumentsIterator: IndexingIterator<[String]>, currentArgument: String) { self.associatedArgumentValue = associatedArgumentValue self.argumentsIterator = argumentsIterator self.currentArgument = currentArgument } mutating func next() -> String? { return argumentsIterator.next() } func peek() -> String? { var iteratorCopy = argumentsIterator let nextArgument = iteratorCopy.next() return nextArgument } } /// Parses the provided array and return the result. public func parse(_ arguments: [String] = []) throws -> Result { return try parse(arguments, parent: nil) } private func parse(_ arguments: [String] = [], parent: Result?) throws -> Result { let result = Result(parser: self, parent: parent) // Create options map to quickly look up the arguments. let optionsTuple = optionArguments.flatMap({ option -> [(String, AnyArgument)] in var result = [(option.name, option)] // Add the short names too, if we have them. if let shortName = option.shortName { result += [(shortName, option)] } return result }) let optionsMap = Dictionary(uniqueKeysWithValues: optionsTuple) // Create iterators. var positionalArgumentIterator = positionalArguments.makeIterator() var argumentsIterator = arguments.makeIterator() while let argumentString = argumentsIterator.next() { let argument: AnyArgument let parser: Parser // If argument is help then just print usage and exit. if argumentString == "-h" || argumentString == "-help" || argumentString == "--help" { printUsage(on: stdoutStream) exit(0) } else if isPositional(argument: argumentString) { /// If this parser has subparsers, we allow only one positional argument which is the subparser command. if !subparsers.isEmpty { // Make sure this argument has a subparser. guard let subparser = subparsers[argumentString] else { throw ArgumentParserError.expectedArguments(self, Array(subparsers.keys)) } // Save which subparser was chosen. result.subparser = argumentString // Parse reset of the arguments with the subparser. return try subparser.parse(Array(argumentsIterator), parent: result) } // Get the next positional argument we are expecting. guard let positionalArgument = positionalArgumentIterator.next() else { throw ArgumentParserError.unexpectedArgument(argumentString) } argument = positionalArgument parser = Parser( associatedArgumentValue: nil, argumentsIterator: argumentsIterator, currentArgument: argumentString) } else { let (argumentString, value) = argumentString.spm_split(around: "=") // Get the corresponding option for the option argument. guard let optionArgument = optionsMap[argumentString] else { let suggestion = bestMatch(for: argumentString, from: Array(optionsMap.keys)) throw ArgumentParserError.unknownOption(argumentString, suggestion: suggestion) } argument = optionArgument parser = Parser( associatedArgumentValue: value, argumentsIterator: argumentsIterator, currentArgument: argumentString) } // Update results. var parserProtocol = parser as ArgumentParserProtocol let values = try argument.parse(with: &parserProtocol) try result.add(values, for: argument) // Restore the argument iterator state. argumentsIterator = (parserProtocol as! Parser).argumentsIterator } // Report if there are any non-optional positional arguments left which were not present in the arguments. let leftOverArguments = Array(positionalArgumentIterator) if leftOverArguments.contains(where: { !$0.isOptional }) { throw ArgumentParserError.expectedArguments(self, leftOverArguments.map({ $0.name })) } return result } /// Prints usage text for this parser on the provided stream. public func printUsage(on stream: WritableByteStream) { /// Space settings. let maxWidthDefault = 24 let padding = 2 let maxWidth: Int // Determine the max width based on argument length or choose the // default width if max width is longer than the default width. if let maxArgument = (positionalArguments + optionArguments).map({ [$0.name, $0.shortName].compactMap({ $0 }).joined(separator: ", ").count }).max(), maxArgument < maxWidthDefault { maxWidth = maxArgument + padding + 1 } else { maxWidth = maxWidthDefault } /// Prints an argument on a stream if it has usage. func print(formatted argument: String, usage: String, on stream: WritableByteStream) { // Start with a new line and add some padding. stream <<< "\n" <<< Format.asRepeating(string: " ", count: padding) let count = argument.count // If the argument is longer than the max width, print the usage // on a new line. Otherwise, print the usage on the same line. if count >= maxWidth - padding { stream <<< argument <<< "\n" // Align full width because usage is to be printed on a new line. stream <<< Format.asRepeating(string: " ", count: maxWidth + padding) } else { stream <<< argument // Align to the remaining empty space on the line. stream <<< Format.asRepeating(string: " ", count: maxWidth - count) } stream <<< usage } stream <<< "OVERVIEW: " <<< overview if !usage.isEmpty { stream <<< "\n\n" // Get the binary name from command line arguments. let defaultCommandName = CommandLine.arguments[0].components(separatedBy: "/").last! stream <<< "USAGE: " <<< (commandName ?? defaultCommandName) <<< " " <<< usage } if optionArguments.count > 0 { stream <<< "\n\n" stream <<< "OPTIONS:" for argument in optionArguments.lazy.sorted(by: { $0.name < $1.name }) { guard let usage = argument.usage else { continue } // Create name with its shortname, if available. let name = [argument.name, argument.shortName].compactMap({ $0 }).joined(separator: ", ") print(formatted: name, usage: usage, on: stream) } // Print help option, if this is a top level command. if !isSubparser { print(formatted: "--help", usage: "Display available options", on: stream) } } if subparsers.keys.count > 0 { stream <<< "\n\n" stream <<< "SUBCOMMANDS:" for (command, parser) in subparsers.sorted(by: { $0.key < $1.key }) { // Special case for hidden subcommands. guard !parser.overview.isEmpty else { continue } print(formatted: command, usage: parser.overview, on: stream) } } if positionalArguments.count > 0 { stream <<< "\n\n" stream <<< "POSITIONAL ARGUMENTS:" for argument in positionalArguments { guard let usage = argument.usage else { continue } print(formatted: argument.name, usage: usage, on: stream) } } if let seeAlso = seeAlso { stream <<< "\n\n" stream <<< "SEE ALSO: \(seeAlso)" } stream <<< "\n" stream.flush() } } /// A class to bind ArgumentParser's arguments to an option structure. // deprecated 2/2021 @available(*, deprecated, message: "use swift-argument-parser instead") public final class ArgumentBinder<Options> { /// The signature of body closure. private typealias BodyClosure = (inout Options, ArgumentParser.Result) throws -> Void /// This array holds the closures which should be executed to fill the options structure. private var bodies = [BodyClosure]() /// Create a binder. public init() { } /// Bind an option argument. public func bind<T>( option: OptionArgument<T>, to body: @escaping (inout Options, T) throws -> Void ) { addBody { guard let result = $1.get(option) else { return } try body(&$0, result) } } /// Bind an array option argument. public func bindArray<T>( option: OptionArgument<[T]>, to body: @escaping (inout Options, [T]) throws -> Void ) { addBody { guard let result = $1.get(option) else { return } try body(&$0, result) } } /// Bind a positional argument. public func bind<T>( positional: PositionalArgument<T>, to body: @escaping (inout Options, T) throws -> Void ) { addBody { // All the positional argument will always be present. guard let result = $1.get(positional) else { return } try body(&$0, result) } } /// Bind an array positional argument. public func bindArray<T>( positional: PositionalArgument<[T]>, to body: @escaping (inout Options, [T]) throws -> Void ) { addBody { // All the positional argument will always be present. guard let result = $1.get(positional) else { return } try body(&$0, result) } } /// Bind two positional arguments. public func bindPositional<T, U>( _ first: PositionalArgument<T>, _ second: PositionalArgument<U>, to body: @escaping (inout Options, T, U) throws -> Void ) { addBody { // All the positional arguments will always be present. guard let first = $1.get(first) else { return } guard let second = $1.get(second) else { return } try body(&$0, first, second) } } /// Bind three positional arguments. public func bindPositional<T, U, V>( _ first: PositionalArgument<T>, _ second: PositionalArgument<U>, _ third: PositionalArgument<V>, to body: @escaping (inout Options, T, U, V) throws -> Void ) { addBody { // All the positional arguments will always be present. guard let first = $1.get(first) else { return } guard let second = $1.get(second) else { return } guard let third = $1.get(third) else { return } try body(&$0, first, second, third) } } /// Bind two options. public func bind<T, U>( _ first: OptionArgument<T>, _ second: OptionArgument<U>, to body: @escaping (inout Options, T?, U?) throws -> Void ) { addBody { try body(&$0, $1.get(first), $1.get(second)) } } /// Bind three options. public func bind<T, U, V>( _ first: OptionArgument<T>, _ second: OptionArgument<U>, _ third: OptionArgument<V>, to body: @escaping (inout Options, T?, U?, V?) throws -> Void ) { addBody { try body(&$0, $1.get(first), $1.get(second), $1.get(third)) } } /// Bind two array options. public func bindArray<T, U>( _ first: OptionArgument<[T]>, _ second: OptionArgument<[U]>, to body: @escaping (inout Options, [T], [U]) throws -> Void ) { addBody { try body(&$0, $1.get(first) ?? [], $1.get(second) ?? []) } } /// Add three array option and call the final closure with their values. public func bindArray<T, U, V>( _ first: OptionArgument<[T]>, _ second: OptionArgument<[U]>, _ third: OptionArgument<[V]>, to body: @escaping (inout Options, [T], [U], [V]) throws -> Void ) { addBody { try body(&$0, $1.get(first) ?? [], $1.get(second) ?? [], $1.get(third) ?? []) } } /// Bind a subparser. public func bind( parser: ArgumentParser, to body: @escaping (inout Options, String) throws -> Void ) { addBody { guard let result = $1.subparser(parser) else { return } try body(&$0, result) } } /// Appends a closure to bodies array. private func addBody(_ body: @escaping BodyClosure) { bodies.append(body) } /// Fill the result into the options structure, /// throwing if one of the user-provided binder function throws. public func fill(parseResult result: ArgumentParser.Result, into options: inout Options) throws { try bodies.forEach { try $0(&options, result) } } /// Fill the result into the options structure. @available(*, deprecated, renamed: "fill(parseResult:into:)") public func fill(_ result: ArgumentParser.Result, into options: inout Options) { try! fill(parseResult: result, into: &options) } }
c59980920beb0c7bd3f4aab42cf70212
35.957215
158
0.628084
false
false
false
false
Dimillian/SwiftHN
refs/heads/master
SwiftHNShared/Extension/NSDate+TimeAgo.swift
gpl-2.0
1
// // NSDate+Extension.swift // Tasty // // Created by Vitaliy Kuzmenko on 17/10/14. // http://github.com/vitkuzmenko // Copyright (c) 2014 Vitaliy Kuz'menko. All rights reserved. // import Foundation func NSDateTimeAgoLocalizedStrings(key: String) -> String { let resourcePath: String? if let frameworkBundle = NSBundle(identifier: "com.kevinlawler.NSDateTimeAgo") { // Load from Framework resourcePath = frameworkBundle.resourcePath } else { // Load from Main Bundle resourcePath = NSBundle.mainBundle().resourcePath } if resourcePath == nil { return "" } let path = NSURL(fileURLWithPath: resourcePath!).URLByAppendingPathComponent("NSDateTimeAgo.bundle") guard let bundle = NSBundle(URL: path) else { return "" } return NSLocalizedString(key, tableName: "NSDateTimeAgo", bundle: bundle, comment: "") } extension NSDate { // shows 1 or two letter abbreviation for units. // does not include 'ago' text ... just {value}{unit-abbreviation} // does not include interim summary options such as 'Just now' public var timeAgoSimple: String { let components = self.dateComponents() if components.year > 0 { return stringFromFormat("%%d%@yr", withValue: components.year) } if components.month > 0 { return stringFromFormat("%%d%@mo", withValue: components.month) } // TODO: localize for other calanders if components.day >= 7 { let value = components.day/7 return stringFromFormat("%%d%@w", withValue: value) } if components.day > 0 { return stringFromFormat("%%d%@d", withValue: components.day) } if components.hour > 0 { return stringFromFormat("%%d%@h", withValue: components.hour) } if components.minute > 0 { return stringFromFormat("%%d%@m", withValue: components.minute) } if components.second > 0 { return stringFromFormat("%%d%@s", withValue: components.second ) } return "" } public var timeAgo: String { let components = self.dateComponents() if components.year > 0 { if components.year < 2 { return NSDateTimeAgoLocalizedStrings("Last year") } else { return stringFromFormat("%%d %@years ago", withValue: components.year) } } if components.month > 0 { if components.month < 2 { return NSDateTimeAgoLocalizedStrings("Last month") } else { return stringFromFormat("%%d %@months ago", withValue: components.month) } } // TODO: localize for other calanders if components.day >= 7 { let week = components.day/7 if week < 2 { return NSDateTimeAgoLocalizedStrings("Last week") } else { return stringFromFormat("%%d %@weeks ago", withValue: week) } } if components.day > 0 { if components.day < 2 { return NSDateTimeAgoLocalizedStrings("Yesterday") } else { return stringFromFormat("%%d %@days ago", withValue: components.day) } } if components.hour > 0 { if components.hour < 2 { return NSDateTimeAgoLocalizedStrings("An hour ago") } else { return stringFromFormat("%%d %@hours ago", withValue: components.hour) } } if components.minute > 0 { if components.minute < 2 { return NSDateTimeAgoLocalizedStrings("A minute ago") } else { return stringFromFormat("%%d %@minutes ago", withValue: components.minute) } } if components.second > 0 { if components.second < 5 { return NSDateTimeAgoLocalizedStrings("Just now") } else { return stringFromFormat("%%d %@seconds ago", withValue: components.second) } } return "" } private func dateComponents() -> NSDateComponents { let calander = NSCalendar.currentCalendar() return calander.components([.Second, .Minute, .Hour, .Day, .Month, .Year], fromDate: self, toDate: NSDate(), options: []) } private func stringFromFormat(format: String, withValue value: Int) -> String { let localeFormat = String(format: format, getLocaleFormatUnderscoresWithValue(Double(value))) return String(format: NSDateTimeAgoLocalizedStrings(localeFormat), value) } private func getLocaleFormatUnderscoresWithValue(value: Double) -> String { guard let localeCode = NSLocale.preferredLanguages().first else { return "" } // Russian (ru) and Ukrainian (uk) if localeCode == "ru" || localeCode == "uk" { let XY = Int(floor(value)) % 100 let Y = Int(floor(value)) % 10 if Y == 0 || Y > 4 || (XY > 10 && XY < 15) { return "" } if Y > 1 && Y < 5 && (XY < 10 || XY > 20) { return "_" } if Y == 1 && XY != 11 { return "__" } } return "" } }
dde2f324d807d098a18c0638468f02f8
31.068182
129
0.53331
false
false
false
false
Jnosh/swift
refs/heads/master
test/stdlib/DispatchDeprecationWatchOS.swift
apache-2.0
30
// RUN: %swift -typecheck -target i386-apple-watchos2.0 -verify -sdk %sdk %s // REQUIRES: CPU=i386, OS=watchos // REQUIRES: objc_interop import Foundation import Dispatch // These are deprecated on all versions of watchOS. _ = DispatchQueue.GlobalQueuePriority.high // expected-warning {{'high' is deprecated on watchOS: Use qos attributes instead}} _ = DispatchQueue.GlobalQueuePriority.default // expected-warning {{'default' is deprecated on watchOS: Use qos attributes instead}} _ = DispatchQueue.GlobalQueuePriority.low // expected-warning {{'low' is deprecated on watchOS: Use qos attributes instead}} let b = DispatchQueue.GlobalQueuePriority.background // expected-warning {{'background' is deprecated on watchOS: Use qos attributes instead}} _ = DispatchQueue.global(priority:b) // expected-warning {{'global(priority:)' is deprecated on watchOS}}
0043cd4a6d717fcbd91a0863a2e7aa92
60.571429
142
0.766821
false
false
false
false
safx/iOS9-InterApp-DnD-Demo
refs/heads/master
SampleX/ViewController.swift
mit
1
// // ViewController.swift // SampleX // // Created by Safx Developer on 2015/09/27. // // import UIKit class ViewController: UIViewController { @IBOutlet weak var bundleLabel: UILabel! { didSet { bundleLabel.text = myID.componentsSeparatedByString(".").last } } @IBOutlet weak var otherLabel: UILabel! private var previousData: String = "" private var queue: dispatch_queue_t! private var timer: dispatch_source_t! private var model: [Shape] = [] private var draggingModelIndex: Int = -1 private var dragOffset: CGPoint! = CGPointZero private var modelOfOtherProcess: Shape? private lazy var myPasteboard: UIPasteboard = { return UIPasteboard(name: self.myID, create: true)! }() private var myID: String = NSBundle.mainBundle().bundleIdentifier! private lazy var otherID: String = { return self.myID == "com.blogspot.safx-dev.SampleX" ? "com.blogspot.safx-dev.SampleY" : "com.blogspot.safx-dev.SampleX" }() deinit { UIPasteboard.removePasteboardWithName(myID) } override func viewDidLoad() { super.viewDidLoad() (view as! ShapeView).delegate = self if myID == "com.blogspot.safx-dev.SampleX" { model.append(.Rectangle(pos: CGPointMake(80, 280), size: CGSizeMake(80, 80), color: UIColor.blueColor())) model.append(.Ellipse(pos: CGPointMake(20, 220), size: CGSizeMake(50, 50), color: UIColor.redColor())) } else { model.append(.Rectangle(pos: CGPointMake(80, 320), size: CGSizeMake(50, 50), color: UIColor.greenColor())) model.append(.Ellipse(pos: CGPointMake(20, 220), size: CGSizeMake(80, 80), color: UIColor.cyanColor())) } queue = myID.withCString { dispatch_queue_create($0, nil) } timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) dispatch_source_set_timer(timer, dispatch_time_t(DISPATCH_TIME_NOW), USEC_PER_SEC * 50, 0) dispatch_source_set_event_handler(timer) { () -> Void in self.updateModelOfOtherProcess() } dispatch_resume(timer) } private func updateModelOfOtherProcess() { assert(NSThread.mainThread() != NSThread.currentThread()) if let otherpb = UIPasteboard(name: otherID, create: false), s = otherpb.string where s != previousData { previousData = s let ss = s.componentsSeparatedByString(",") switch (ss[0], ss.count) { case ("B", 7): // touchBegan let size = ss[2...3].flatMap{Int($0)}.flatMap{CGFloat($0)} let offset = ss[5...6].flatMap{Int($0)}.flatMap{CGFloat($0)} if let shape = Shape.createShape(ss[1], size: CGSizeMake(size[0], size[1]), color: ss[4]) { modelOfOtherProcess = shape dragOffset = CGPointMake(offset[0], offset[1]) } case ("M", 3): // touchMoved if modelOfOtherProcess == nil { return } let ns = ss[1...2].flatMap{Int($0)}.flatMap{CGFloat($0)} let x = ns[0] let p = CGPointMake(x >= 0 ? x : view.frame.size.width + x, ns[1]) modelOfOtherProcess!.changePosition(CGPointMake(dragOffset.x + p.x, dragOffset.y + p.y)) case ("O", 1): // touchMoved but model is still contained in other view if modelOfOtherProcess == nil { return } let p = CGPointMake(-10000, -10000) // FIXME modelOfOtherProcess!.changePosition(p) case ("E", 1): // touchEnded if modelOfOtherProcess == nil { return } model.append(modelOfOtherProcess!) modelOfOtherProcess = nil case ("C", 1): fallthrough // touchCancelled default: modelOfOtherProcess = nil } dispatch_async(dispatch_get_main_queue()) { () -> Void in self.otherLabel.text = s self.view.setNeedsDisplay() } } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) let p = touches.first!.locationInView(view) for (idx, e) in model.enumerate() { if e.isClicked(p) { draggingModelIndex = idx let m = model[draggingModelIndex] dragOffset = CGPointMake(m.position.x - p.x, m.position.y - p.y) myPasteboard.string = "B,\(m.string),\(Int(dragOffset.x)),\(Int(dragOffset.y))" return } } draggingModelIndex = -1 } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event) if 0 > draggingModelIndex || draggingModelIndex >= model.count { return } let p = touches.first!.locationInView(view) model[draggingModelIndex].changePosition(CGPointMake(dragOffset.x + p.x, dragOffset.y + p.y)) let f = view.frame if p.x < f.minX { myPasteboard.string = "M,\(Int(p.x-0.5)),\(Int(p.y))" } else if f.maxX <= p.x { myPasteboard.string = "M,\(Int(p.x-f.maxX)),\(Int(p.y))" } else { myPasteboard.string = "O" } view.setNeedsDisplay() } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) myPasteboard.string = "C" draggingModelIndex = -1 } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) if 0 > draggingModelIndex || draggingModelIndex >= model.count { return } let p = touches.first!.locationInView(view) model[draggingModelIndex].changePosition(CGPointMake(dragOffset.x + p.x, dragOffset.y + p.y)) if view.frame.contains(p) { myPasteboard.string = "C" } else { myPasteboard.string = "E" model.removeAtIndex(draggingModelIndex) } view.setNeedsDisplay() draggingModelIndex = -1 } override func viewDidLayoutSubviews() { view.setNeedsDisplay() } } extension ViewController: ShapeViewDelegate { func draw(rect: CGRect) { model.forEach { $0.draw() } modelOfOtherProcess?.draw() } }
7cf5ac8d9a71adb22d8f8d1abbd67314
35.751412
127
0.591852
false
false
false
false
hanwanjie853710069/Easy-living
refs/heads/master
易持家/Class/Class_project/ECAdd/Controller/ELAddressVC.swift
apache-2.0
1
// // ELAddressVC.swift // EasyLiving // // Created by 王木木 on 16/5/26. // Copyright © 2016年 王木木. All rights reserved. // import UIKit class ELAddressVC: CMBaseViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{ lazy var tableView : UITableView = { let tabV = UITableView.init(frame: self.view.bounds, style: .Plain) tabV.delegate = self tabV.dataSource = self tabV.tableFooterView = UIView() tabV.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20) return tabV }() var funcBlock = {(cityids:String ,cityName:String)->() in} let cellid = "cellid" var arrayData :NSMutableArray = [] var arrayTemp :NSMutableArray = [] lazy var searchbar:UISearchBar = { let searc = UISearchBar.init(frame: CGRectMake(0, 0, ScreenWidth, 40)) searc.delegate = self return searc }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "地点" self.view.backgroundColor = UIColor.whiteColor() self.view.addSubview(self.tableView) getData() } }
88b1d02ef41e35acd8daafdd47f88777
23.48
75
0.61683
false
false
false
false
jimmy54/iRime
refs/heads/master
iRime/Keyboard/tasty-imitation-keyboard/Views/KeyboardKeyBackground.swift
gpl-3.0
1
// // KeyboardKeyBackground.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/19/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // import UIKit // This class does not actually draw its contents; rather, it generates bezier curves for others to use. // (You can still move it around, resize it, and add subviews to it. It just won't display the curve assigned to it.) class KeyboardKeyBackground: UIView, Connectable { var fillPath: UIBezierPath? var underPath: UIBezierPath? var edgePaths: [UIBezierPath]? // do not set this manually var cornerRadius: CGFloat var underOffset: CGFloat var startingPoints: [CGPoint] var segmentPoints: [(CGPoint, CGPoint)] var arcCenters: [CGPoint] var arcStartingAngles: [CGFloat] var dirty: Bool var attached: Direction? { didSet { self.dirty = true self.setNeedsLayout() } } var hideDirectionIsOpposite: Bool { didSet { self.dirty = true self.setNeedsLayout() } } init(cornerRadius: CGFloat, underOffset: CGFloat) { attached = nil hideDirectionIsOpposite = false dirty = false startingPoints = [] segmentPoints = [] arcCenters = [] arcStartingAngles = [] startingPoints.reserveCapacity(4) segmentPoints.reserveCapacity(4) arcCenters.reserveCapacity(4) arcStartingAngles.reserveCapacity(4) for _ in 0..<4 { startingPoints.append(CGPoint.zero) segmentPoints.append((CGPoint.zero, CGPoint.zero)) arcCenters.append(CGPoint.zero) arcStartingAngles.append(0) } self.cornerRadius = cornerRadius self.underOffset = underOffset super.init(frame: CGRect.zero) self.isUserInteractionEnabled = false } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } var oldBounds: CGRect? override func layoutSubviews() { if !self.dirty { if self.bounds.width == 0 || self.bounds.height == 0 { return } if oldBounds != nil && self.bounds.equalTo(oldBounds!) { return } } oldBounds = self.bounds super.layoutSubviews() self.generatePointsForDrawing(self.bounds) self.dirty = false } let floatPi = CGFloat(Double.pi) let floatPiDiv2 = CGFloat(Double.pi/2.0) let floatPiDivNeg2 = -CGFloat(Double.pi/2.0) func generatePointsForDrawing(_ bounds: CGRect) { let segmentWidth = bounds.width let segmentHeight = bounds.height - CGFloat(underOffset) // base, untranslated corner points self.startingPoints[0] = CGPoint(x: 0, y: segmentHeight) self.startingPoints[1] = CGPoint(x: 0, y: 0) self.startingPoints[2] = CGPoint(x: segmentWidth, y: 0) self.startingPoints[3] = CGPoint(x: segmentWidth, y: segmentHeight) self.arcStartingAngles[0] = floatPiDiv2 self.arcStartingAngles[2] = floatPiDivNeg2 self.arcStartingAngles[1] = floatPi self.arcStartingAngles[3] = 0 //// actual coordinates for each edge, including translation //self.segmentPoints.removeAll(keepCapacity: true) // //// actual coordinates for arc centers for each corner //self.arcCenters.removeAll(keepCapacity: true) // //self.arcStartingAngles.removeAll(keepCapacity: true) for i in 0 ..< self.startingPoints.count { let currentPoint = self.startingPoints[i] let nextPoint = self.startingPoints[(i + 1) % self.startingPoints.count] var floatXCorner: CGFloat = 0 var floatYCorner: CGFloat = 0 if (i == 1) { floatXCorner = cornerRadius } else if (i == 3) { floatXCorner = -cornerRadius } if (i == 0) { floatYCorner = -cornerRadius } else if (i == 2) { floatYCorner = cornerRadius } let p0 = CGPoint( x: currentPoint.x + (floatXCorner), y: currentPoint.y + underOffset + (floatYCorner)) let p1 = CGPoint( x: nextPoint.x - (floatXCorner), y: nextPoint.y + underOffset - (floatYCorner)) self.segmentPoints[i] = (p0, p1) let c = CGPoint( x: p0.x - (floatYCorner), y: p0.y + (floatXCorner)) self.arcCenters[i] = c } // order of edge drawing: left edge, down edge, right edge, up edge // We need to have separate paths for all the edges so we can toggle them as needed. // Unfortunately, it doesn't seem possible to assemble the connected fill path // by simply using CGPathAddPath, since it closes all the subpaths, so we have to // duplicate the code a little bit. let fillPath = UIBezierPath() var edgePaths: [UIBezierPath] = [] var prevPoint: CGPoint? for i in 0..<4 { var edgePath: UIBezierPath? let segmentPoint = self.segmentPoints[i] if self.attached != nil && (self.hideDirectionIsOpposite ? self.attached!.rawValue != i : self.attached!.rawValue == i) { // do nothing // TODO: quick hack if !self.hideDirectionIsOpposite { continue } } else { edgePath = UIBezierPath() // TODO: figure out if this is ncessary if prevPoint == nil { prevPoint = segmentPoint.0 fillPath.move(to: prevPoint!) } fillPath.addLine(to: segmentPoint.0) fillPath.addLine(to: segmentPoint.1) edgePath!.move(to: segmentPoint.0) edgePath!.addLine(to: segmentPoint.1) prevPoint = segmentPoint.1 } let shouldDrawArcInOppositeMode = (self.attached != nil ? (self.attached!.rawValue == i) || (self.attached!.rawValue == ((i + 1) % 4)) : false) if (self.attached != nil && (self.hideDirectionIsOpposite ? !shouldDrawArcInOppositeMode : self.attached!.rawValue == ((i + 1) % 4))) { // do nothing } else { edgePath = (edgePath == nil ? UIBezierPath() : edgePath) if prevPoint == nil { prevPoint = segmentPoint.1 fillPath.move(to: prevPoint!) } let startAngle = self.arcStartingAngles[(i + 1) % 4] let endAngle = startAngle + floatPiDiv2 let arcCenter = self.arcCenters[(i + 1) % 4] fillPath.addLine(to: prevPoint!) fillPath.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) edgePath!.move(to: prevPoint!) edgePath!.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) prevPoint = self.segmentPoints[(i + 1) % 4].0 } edgePath?.apply(CGAffineTransform(translationX: 0, y: -self.underOffset)) if edgePath != nil { edgePaths.append(edgePath!) } } fillPath.close() fillPath.apply(CGAffineTransform(translationX: 0, y: -self.underOffset)) let underPath = { () -> UIBezierPath in let underPath = UIBezierPath() underPath.move(to: self.segmentPoints[2].1) var startAngle = self.arcStartingAngles[3] var endAngle = startAngle + CGFloat(Double.pi/2.0) underPath.addArc(withCenter: self.arcCenters[3], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true) underPath.addLine(to: self.segmentPoints[3].1) startAngle = self.arcStartingAngles[0] endAngle = startAngle + CGFloat(Double.pi/2.0) underPath.addArc(withCenter: self.arcCenters[0], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true) underPath.addLine(to: CGPoint(x: self.segmentPoints[0].0.x, y: self.segmentPoints[0].0.y - self.underOffset)) startAngle = self.arcStartingAngles[1] endAngle = startAngle - CGFloat(Double.pi/2.0) underPath.addArc(withCenter: CGPoint(x: self.arcCenters[0].x, y: self.arcCenters[0].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false) underPath.addLine(to: CGPoint(x: self.segmentPoints[2].1.x - self.cornerRadius, y: self.segmentPoints[2].1.y + self.cornerRadius - self.underOffset)) startAngle = self.arcStartingAngles[0] endAngle = startAngle - CGFloat(Double.pi/2.0) underPath.addArc(withCenter: CGPoint(x: self.arcCenters[3].x, y: self.arcCenters[3].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false) underPath.close() return underPath }() self.fillPath = fillPath self.edgePaths = edgePaths self.underPath = underPath } func attachmentPoints(_ direction: Direction) -> (CGPoint, CGPoint) { let returnValue = ( self.segmentPoints[direction.clockwise().rawValue].0, self.segmentPoints[direction.counterclockwise().rawValue].1) return returnValue } func attachmentDirection() -> Direction? { return self.attached } func attach(_ direction: Direction?) { self.attached = direction } }
6612a6f30881aced57cb14988e5549cc
36.217544
216
0.558688
false
false
false
false
CD1212/Doughnut
refs/heads/master
Doughnut/Views/TaskManagerView.swift
gpl-3.0
1
/* * Doughnut Podcast Client * Copyright (C) 2017 Chris Dyer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Cocoa class TaskManagerView: NSView, TaskQueueViewDelegate { let activitySpinner = ActivityIndicator() let popover = NSPopover() var tasksViewController: TasksViewController? var hasActiveTasks: Bool = false { didSet { activitySpinner.isHidden = !hasActiveTasks } } required init?(coder decoder: NSCoder) { super.init(coder: decoder) Library.global.tasks.delegate = self popover.behavior = .transient activitySpinner.frame = self.bounds activitySpinner.isHidden = true addSubview(activitySpinner) let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) tasksViewController = (storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "TasksPopover")) as! TasksViewController) tasksViewController?.loadView() // Important: force load views so they exist even before popover is viewed popover.contentViewController = tasksViewController } override func mouseDown(with event: NSEvent) { if hasActiveTasks { popover.show(relativeTo: bounds, of: activitySpinner, preferredEdge: .minY) } } func taskPushed(task: Task) { tasksViewController?.taskPushed(task: task) } func taskFinished(task: Task) { tasksViewController?.taskFinished(task: task) } func tasksRunning(_ running: Bool) { if running { hasActiveTasks = true } else { hasActiveTasks = false if popover.isShown { popover.close() } } } }
6d866663f99836025e550449cee41795
28.636364
156
0.706398
false
false
false
false
mmllr/CleanTweeter
refs/heads/master
CleanTweeter/UseCases/TweetList/UI/Wireframe/iOS/TweetListWireframe.swift
mit
1
import Foundation import UIKit class TweetListWireframe { let viewController: TweetListTableViewController let interactor: TweetListInteractor let presenter: TweetListPresenter init(userRepository: UserRepository) { viewController = UIStoryboard(name: "TweetList", bundle:nil).instantiateInitialViewController() as! TweetListTableViewController interactor = TweetListInteractor(repository: userRepository) presenter = TweetListPresenter(resourceFactory: MobileResourceFactory()) interactor.output = presenter presenter.view = viewController presenter.interactor = interactor viewController.moduleInterface = presenter } }
f5a70f62a2677847faa5ab94e714cb78
31.25
130
0.827907
false
false
false
false
icylydia/PlayWithLeetCode
refs/heads/master
153. Find Minimum in Rotated Sorted Array/solution.swift
mit
1
class Solution { func findMin(nums: [Int]) -> Int { if nums.count == 1 { return nums[0] } if nums.count == 2 { return min(nums[0], nums[1]) } if nums.first! < nums.last! { return nums.first! } let mid = (nums.count - 1) / 2 if nums[0] < nums[mid] { return findMin(Array(nums[(mid + 1)..<nums.count])) } else { return findMin(Array(nums[0...mid])) } } }
c16fa5c1af49c414fc1308c2b215ac16
25.368421
63
0.436
false
false
false
false
thiagolioy/Notes
refs/heads/master
Tests/MinorSeventhChordSpec.swift
mit
1
// // MinorSeventhChordSpec.swift // Notes // // Created by Thiago Lioy on 27/08/17. // Copyright © 2017 com.tplioy. All rights reserved. // import Foundation import Quick import Nimble @testable import Notes class MinorSeventhChordSpec: QuickSpec { override func spec() { describe("Minor Seventh Chord") { var chord: MinorSeventhChord! beforeEach { let key = Note(name: .C, intonation: .natural) chord = MinorSeventhChord(key: key) } it("should have the expected symbol") { expect(chord.symbol).to(equal("m7")) } it("should have the expected intervals") { expect(chord.chordIntervals).to(equal([ .root, .minorThird, .perfectFifth, .minorSeventh ])) } context("in the key of C natural") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .C, intonation: .natural) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("Cm7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .C, intonation: .natural), Note(name: .E, intonation: .flat), Note(name: .G, intonation: .natural), Note(name: .B, intonation: .flat) ])) } } context("in the key of C sharp") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .C, intonation: .sharp) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("C♯m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .C, intonation: .sharp), Note(name: .E, intonation: .natural), Note(name: .G, intonation: .sharp), Note(name: .B, intonation: .natural) ])) } } context("in the key of D flat") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .D, intonation: .flat) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("D♭m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .D, intonation: .flat), Note(name: .F, intonation: .flat), Note(name: .A, intonation: .flat), Note(name: .C, intonation: .flat) ])) } } context("in the key of D natural") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .D, intonation: .natural) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("Dm7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .D, intonation: .natural), Note(name: .F, intonation: .natural), Note(name: .A, intonation: .natural), Note(name: .C, intonation: .natural) ])) } } context("in the key of D sharp") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .D, intonation: .sharp) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("D♯m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .D, intonation: .sharp), Note(name: .F, intonation: .sharp), Note(name: .A, intonation: .sharp), Note(name: .C, intonation: .sharp) ])) } } context("in the key of E flat") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .E, intonation: .flat) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("E♭m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .E, intonation: .flat), Note(name: .G, intonation: .flat), Note(name: .B, intonation: .flat), Note(name: .D, intonation: .flat) ])) } } context("in the key of E natural") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .E, intonation: .natural) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("Em7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .E, intonation: .natural), Note(name: .G, intonation: .natural), Note(name: .B, intonation: .natural), Note(name: .D, intonation: .natural) ])) } } context("in the key of F natural") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .F, intonation: .natural) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("Fm7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .F, intonation: .natural), Note(name: .A, intonation: .flat), Note(name: .C, intonation: .natural), Note(name: .E, intonation: .flat) ])) } } context("in the key of F sharp") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .F, intonation: .sharp) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("F♯m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .F, intonation: .sharp), Note(name: .A, intonation: .natural), Note(name: .C, intonation: .sharp), Note(name: .E, intonation: .natural) ])) } } context("in the key of G flat") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .G, intonation: .flat) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("G♭m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .G, intonation: .flat), Note(name: .B, intonation: .doubleFlat), Note(name: .D, intonation: .flat), Note(name: .F, intonation: .flat) ])) } } context("in the key of G natural") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .G, intonation: .natural) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("Gm7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .G, intonation: .natural), Note(name: .B, intonation: .flat), Note(name: .D, intonation: .natural), Note(name: .F, intonation: .natural) ])) } } context("in the key of G sharp") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .G, intonation: .sharp) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("G♯m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .G, intonation: .sharp), Note(name: .B, intonation: .natural), Note(name: .D, intonation: .sharp), Note(name: .F, intonation: .sharp) ])) } } context("in the key of A flat") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .A, intonation: .flat) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("A♭m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .A, intonation: .flat), Note(name: .C, intonation: .flat), Note(name: .E, intonation: .flat), Note(name: .G, intonation: .flat) ])) } } context("in the key of A natural") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .A, intonation: .natural) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("Am7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .A, intonation: .natural), Note(name: .C, intonation: .natural), Note(name: .E, intonation: .natural), Note(name: .G, intonation: .natural) ])) } } context("in the key of A sharp") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .A, intonation: .sharp) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("A♯m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .A, intonation: .sharp), Note(name: .C, intonation: .sharp), Note(name: .E, intonation: .sharp), Note(name: .G, intonation: .sharp) ])) } } context("in the key of B flat") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .B, intonation: .flat) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("B♭m7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .B, intonation: .flat), Note(name: .D, intonation: .flat), Note(name: .F, intonation: .natural), Note(name: .A, intonation: .flat) ])) } } context("in the key of B natural") { var rootChord: MinorSeventhChord! beforeEach { let key = Note(name: .B, intonation: .natural) rootChord = MinorSeventhChord(key: key) } it("should have the expected full name") { expect(rootChord.fullName()).to(equal("Bm7")) } it("should have the expected chord tones") { let notes = rootChord.chordTones() expect(notes).to(equal([ Note(name: .B, intonation: .natural), Note(name: .D, intonation: .natural), Note(name: .F, intonation: .sharp), Note(name: .A, intonation: .natural) ])) } } } } }
8f3e9496cabc5edeac78fefabbf665ca
38.654028
66
0.399964
false
false
false
false
rastogigaurav/mTV
refs/heads/master
mTV/mTV/ViewModels/HomeViewModel.swift
mit
1
// // HomeViewModel.swift // mTV // // Created by Gaurav Rastogi on 6/22/17. // Copyright © 2017 Gaurav Rastogi. All rights reserved. // import UIKit enum MovieSections:Int { case topRated=0, upcoming, nowPlaying, popular, totalOrUnknown } class HomeViewModel: NSObject { var topRatedMovies:[Movie]? var upcomingMovies:[Movie]? var nowPlayingMovies:[Movie]? var popularMovies:[Movie]? var displayMovies:DisplayMoviesProtocol var reloadSection:((_ section:MovieSections?)->Void) = {_ in } var currentPage = 1 init(with displayMovies:DisplayMoviesProtocol) { self.displayMovies = displayMovies } func fetchMovies(){ self.displayMovies.displayMovies(forSection: .topRated, withPage: currentPage) {[unowned self] (total,movies,section) in self.topRatedMovies = movies self.reloadSection(section) } self.displayMovies.displayMovies(forSection: .upcoming, withPage: currentPage) {[unowned self] (total,movies,section) in self.upcomingMovies = movies self.reloadSection(section) } self.displayMovies.displayMovies(forSection: .nowPlaying, withPage: currentPage) {[unowned self] (total,movies,section) in self.nowPlayingMovies = movies self.reloadSection(section) } self.displayMovies.displayMovies(forSection: .popular, withPage: currentPage) {[unowned self] (total,movies,section) in self.popularMovies = movies self.reloadSection(section) } } func numberofSections()->Int{ return MovieSections.totalOrUnknown.rawValue } func numberOfItemsInSection(section:Int)->Int{ let movieSection = MovieSections(rawValue: section)! var listForSection:[Movie]? = nil switch movieSection { case .topRated: listForSection = self.topRatedMovies case .upcoming: listForSection = self.upcomingMovies case .nowPlaying: listForSection = self.nowPlayingMovies case .popular: listForSection = self.popularMovies default: return 0 } if let list = listForSection{ if list.count > maximumRowsInSectionOnHomePage{ return maximumRowsInSectionOnHomePage } else{ return list.count } } return 0 } func posterImageForMoviewAtIndexPath(indexPath:IndexPath)->String?{ switch MovieSections(rawValue: indexPath.section)! { case .topRated: if let list = self.topRatedMovies{ return list[indexPath.row].posterPathURL() } case .upcoming: if let list = self.upcomingMovies{ return list[indexPath.row].posterPathURL() } case .nowPlaying: if let list = self.nowPlayingMovies{ return list[indexPath.row].posterPathURL() } case .popular: if let list = self.popularMovies{ return list[indexPath.row].posterPathURL() } default: break } return nil } func section(withTitle title:String)->MovieSections{ switch title { case "Top Rated": return .topRated case "Upcoming": return .upcoming case "Now Playing": return .nowPlaying case "Popular": return .popular default: return .totalOrUnknown } } func movieListBelongsToSection(withTitle title:String)->[Movie]{ switch title { case "Top Rated": return self.topRatedMovies! case "Upcoming": return self.upcomingMovies! case "Now Playing": return self.nowPlayingMovies! case "Popular": return self.popularMovies! default: return [] } } func movieIdForMovie(at indexPath:IndexPath)->Int?{ switch MovieSections(rawValue: indexPath.section)! { case .topRated: return self.topRatedMovies?[indexPath.row].id case .upcoming: return self.upcomingMovies?[indexPath.row].id case .nowPlaying: return self.nowPlayingMovies?[indexPath.row].id case .popular: return self.popularMovies?[indexPath.row].id default: break } return nil } func titleForSection(indexPath:IndexPath)->String?{ switch MovieSections(rawValue: indexPath.section)! { case .topRated: return "Top Rated" case .upcoming: return "Upcoming" case .nowPlaying: return "Now Playing" case .popular: return "Popular" default: break } return nil } }
f06fa064a7efc60aa574c3f3aebc5e54
28.149425
130
0.575513
false
false
false
false
Vanlol/MyYDW
refs/heads/master
SwiftCocoa/Base/Controllers/BaseViewController.swift
apache-2.0
1
// // BaseViewController.swift // SwiftCocoa // // Created by admin on 2017/7/4. // Copyright © 2017年 admin. All rights reserved. // import UIKit class BaseViewController: UIViewController { /** * 记录是否正在显示加载动画 */ public var isHud = false fileprivate lazy var hudView:ProgressHUD = { let vi = ProgressHUD(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)) return vi }() override func viewDidLoad() { super.viewDidLoad() } /** * 显示导航栏 */ public func showNav() { navigationController?.isNavigationBarHidden = false } /** * 隐藏导航栏 */ public func hideNav() { navigationController?.isNavigationBarHidden = true } /** * 设置导航栏阴影 */ public func setUpNavShadow() { navigationController?.navigationBar.layer.shadowColor = 0x3C6CDE.HexColor.cgColor navigationController?.navigationBar.layer.shadowOffset = CGSize.zero navigationController?.navigationBar.layer.shadowOpacity = 0.3 navigationController?.navigationBar.layer.shadowRadius = 4 } /** * 设置导航栏标题,导航栏的标题是"系统的文字,有加粗." */ public func setUpSystemNav(title:String,hexColorBg:Int){ navigationItem.title = title navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.setBackgroundImage(UIImage.colorImage(hex: hexColorBg), for: .any, barMetrics: .default) } /** * 设置导航栏标题,文字颜色与大小等 */ public func setUpCustomNav(title:String,hexColorTitle:UIColor,hexColorBg:Int) { let titleLab = UILabel() titleLab.bounds = CGRect(x: 0, y: 0, width: 150, height: 20) titleLab.text = title titleLab.textAlignment = .center titleLab.textColor = hexColorTitle titleLab.font = UIFont.systemFont(ofSize: 17) navigationItem.titleView = titleLab navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.setBackgroundImage(UIImage.colorImage(hex: hexColorBg), for: .any, barMetrics: .default) } public func tabPushVCWith(storyboardName:String,vcId:String){ let vc = UIStoryboard(name: storyboardName, bundle: nil).instantiateViewController(withIdentifier: vcId) vc.hidesBottomBarWhenPushed = true navigationController?.pushViewController(vc, animated: true) } public func loadingShow() { isHud = true view.addSubview(hudView) hudView.successClosure = {() -> Void in self.isHud = false } } public func loadingDismiss() { hudView.successDismiss() } public func loadingFail() { hudView.failed() } } extension BaseViewController { //获取当前屏幕显示的控制器 public func getCurrentVC() -> UIViewController { var window = UIApplication.shared.keyWindow if window?.windowLevel != UIWindowLevelNormal { let windows = UIApplication.shared.windows for tmpWin in windows { if tmpWin.windowLevel == UIWindowLevelNormal { window = tmpWin break } } } let frontView = window?.subviews[0] let nextResponder = frontView?.next if (nextResponder?.isKind(of: UIViewController.classForCoder()))! { return nextResponder as! UIViewController }else{ return (window?.rootViewController)! } } }
9e54f1e3a498421dd618aa56f68f14b9
27.139535
137
0.626171
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/public/SDK/Foundation/NSArray.swift
apache-2.0
25
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Arrays //===----------------------------------------------------------------------===// extension NSArray : ExpressibleByArrayLiteral { /// Create an instance initialized with `elements`. public required convenience init(arrayLiteral elements: Any...) { // Let bridging take care of it. self.init(array: elements) } } extension Array : _ObjectiveCBridgeable { /// Private initializer used for bridging. /// /// The provided `NSArray` will be copied to ensure that the copy can /// not be mutated by other code. internal init(_cocoaArray: NSArray) { _sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self), "Array can be backed by NSArray only when the element type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFArrayCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFArrayCreateCopy() copies array contents unconditionally, // resulting in O(n) copies even for immutable arrays. // // <rdar://problem/19773555> CFArrayCreateCopy() is >10x slower than // -[NSArray copyWithZone:] // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Array( _immutableCocoaArray: unsafeBitCast(_cocoaArray.copy() as AnyObject, to: _NSArrayCore.self)) } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSArray { return unsafeBitCast(self._bridgeToObjectiveCImpl(), to: NSArray.self) } public static func _forceBridgeFromObjectiveC( _ source: NSArray, result: inout Array? ) { // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source) { result = native return } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) result = Array(_cocoaArray: source) return } result = _arrayForceCast([AnyObject](_cocoaArray: source)) } public static func _conditionallyBridgeFromObjectiveC( _ source: NSArray, result: inout Array? ) -> Bool { // Construct the result array by conditionally bridging each element. let anyObjectArr = [AnyObject](_cocoaArray: source) result = _arrayConditionalCast(anyObjectArr) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ source: NSArray? ) -> Array { // `nil` has historically been used as a stand-in for an empty // array; map it to an empty array instead of failing. if _slowPath(source == nil) { return Array() } // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source!) { return native } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) return Array(_cocoaArray: source!) } return _arrayForceCast([AnyObject](_cocoaArray: source!)) } } extension NSArray : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). final public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } /* TODO: API review extension NSArray : Swift.Collection { final public var startIndex: Int { return 0 } final public var endIndex: Int { return count } } */ extension NSArray { // Overlay: - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: Any...) { self.init(array: elements) } } extension NSArray { /// Initializes a newly allocated array by placing in it the objects /// contained in a given array. /// /// - Returns: An array initialized to contain the objects in /// `anArray``. The returned object might be different than the /// original receiver. /// /// Discussion: After an immutable array has been initialized in /// this way, it cannot be modified. @nonobjc public convenience init(array anArray: NSArray) { self.init(array: anArray as Array) } } extension NSArray : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [AnyObject]) } } extension Array: CVarArg {}
25e275973db63bffa46cb516333d4cc8
30.849057
105
0.648499
false
false
false
false
SmallElephant/FEAlgorithm-Swift
refs/heads/master
10-Number/10-Number/FEArray.swift
mit
1
// // FEArray.swift // 10-Number // // Created by FlyElephant on 17/2/28. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class FEArray { func moreThanHalfNumber(arr:[Int]) -> Int? { if arr.count == 0 { return nil } var target:Int = arr[0] var count:Int = 1 for i in 1..<arr.count { if count == 0 { target = arr[i] count = 1 } else if target == arr[i] { count += 1 } else { count -= 1 } } return target } }
16aa14c7af4bcdcd13457b406b14e9df
18.757576
55
0.427914
false
false
false
false
PrimarySA/Hackaton2015
refs/heads/master
stocker/BachiTrading/Instruments+DataGetters.swift
gpl-3.0
1
// // Instruments+DataGetters.swift // BachiTrading // // Created by Emiliano Bivachi on 15/11/15. // Copyright (c) 2015 Emiliano Bivachi. All rights reserved. // import Foundation extension Instrument { func lastPriceText() -> String { if let marketData = self.marketData { return "$ \(marketData.last.price)" } else { return "--" } } func priceColor() -> UIColor { var color = Styler.Color.greenColor var last = marketData?.last.price var open = marketData?.openPrice if let last = last, open = open where (last-open)/open < 0 { color = Styler.Color.redColor } return color } func getMarketDataWithCompletionBlock(completionBlock: (Instrument, NSError?)->()) { MarketDataStore.sharedInstance().getMarketDataForInstrument(self, withCompletionBlock: { [weak self] (marketDataResponse, error) in if let weakSelf = self { if let marketDataResponse = marketDataResponse as? MarketDataResponse { weakSelf.marketData = marketDataResponse.marketData } completionBlock(weakSelf, error) } }) } func getDataSince(daysAgo: Double, completionBlock: (Instrument, [CGFloat])->()) { HistoricalDataStore().getHistoricalMarketDataForInstrument(self, between: NSDate(timeIntervalSinceNow: -daysAgo*24*60*60), and: NSDate(timeIntervalSinceNow: -24*60*60), withCompletionBlock: { [weak self] (historicalPriceResponse, error) -> Void in if let historicalPriceResponse = historicalPriceResponse as? HistoricalMarketDataResponse, let weakSelf = self { let data = historicalPriceResponse.marketDataH.map { $0 as? Offer }.map { $0!.price } completionBlock(weakSelf, data) } }) } }
4350dac1777fac947df543324918b97a
35.796296
139
0.600201
false
false
false
false
primetimer/PrimeFactors
refs/heads/master
PrimeFactors/Classes/Factorize.swift
mit
1
// // Factorize.swift // PFactors // // Created by Stephan Jancar on 18.10.17. // import Foundation import BigInt public class Factorize { private var method : PFactor public init(method : PFactor) { self.method = method } public func Factorize(n: BigUInt, cancel: CalcCancelProt?) -> [BigUInt] { var nn = n var factors : [BigUInt] = [] while nn > 1 { if nn.isPrime() { factors.append(nn) return factors } let factor = method.GetFactor(n: nn, cancel: cancel) if factor.isPrime() { factors.append(factor) } else { let subfactors = Factorize(n: factor, cancel: cancel) for s in subfactors { factors.append(s) } } nn = nn / factor } return factors } public func Factorize(s: String) -> String { var ans = "" guard let n = BigUInt(s) else { return "" } let factors = Factorize(n: n, cancel: nil) var start = true for f in factors { if !start { ans = ans + "*" } ans.append(String(f)) start = false } return ans } }
fd819ba0e38b9ac94e466b5795c3a971
18.442308
74
0.6182
false
false
false
false
concurlabs/SwiftyConcur
refs/heads/master
Source/ConcurAccessToken.swift
apache-2.0
1
import SwiftyJSON public class ConcurAccessToken { public var ExpirationDate: String! public var InstanceUrl: String! public var RefreshToken: String! public var Token: String! public init(json: JSON) { self.ExpirationDate = json["Expiration_date"].string self.InstanceUrl = json["Instance_Url"].string self.RefreshToken = json["Refresh_Token"].string self.Token = json["Token"].string } public init(accessTokenString: String) { self.Token = accessTokenString } }
7c6145c628341eb5393e9645dbbf4610
23.428571
56
0.708984
false
false
false
false
novi/proconapp
refs/heads/master
ProconApp/ProconBase/UserContext.swift
bsd-3-clause
1
// // UserContext.swift // ProconBase // // Created by ito on 2015/06/13. // Copyright (c) 2015年 Procon. All rights reserved. // import Foundation public protocol UserIdentifier { var id: Int { get } var token: String { get } } struct MeIdentifier: UserIdentifier { var id: Int var token: String init?(id: Int, tokenStr: String?) { if let token = tokenStr as String? { self.id = id self.token = token return } return nil } } public class UserContext { public static let defaultContext = UserContext() public var me: UserIdentifier? { // if nil, not logged in if let me = self.me_ { return me } self.reloadMeInfo() return me_ } var me_: UserIdentifier? public var isLoggedIn: Bool { return me != nil } init() { self.reloadMeInfo() Logger.debug("host:\(Constants.APIBaseURL)") } func reloadMeInfo() { let uds = [NSUserDefaults.standardUserDefaults(), AppGroup.sharedInstance] for ud in uds { me_ = MeIdentifier(id: ud.integerForKey(.UserID), tokenStr: ud.stringForKey(.UserToken)) if me_ != nil { break } } } public func saveAsMe(user: UserIdentifier) { me_ = MeIdentifier(id: user.id, tokenStr: user.token) // save user token to both the app and its extension let uds = [NSUserDefaults.standardUserDefaults(), AppGroup.sharedInstance] for ud in uds { ud.setInteger(user.id, forKey: .UserID) ud.setObject(user.token, forKey: .UserToken) ud.synchronize() } } }
a6f577b3bd979cb718cd2b9acd991619
22.77027
100
0.560546
false
false
false
false
bettkd/KenyaNews
refs/heads/master
KenyaNews/HolderView.swift
apache-2.0
1
// // HolderView.swift // SBLoader // // Created by Satraj Bambra on 2015-03-17. // Copyright (c) 2015 Satraj Bambra. All rights reserved. // import UIKit protocol HolderViewDelegate:class { func animateLabel() } class HolderView: UIView { let ovalLayer = OvalLayer() let triangleLayer = TriangleLayer() let redRectangleLayer = RectangleLayer() let blueRectangleLayer = RectangleLayer() let arcLayer = ArcLayer() var parentFrame :CGRect = CGRectZero weak var delegate:HolderViewDelegate? override init(frame: CGRect) { super.init(frame: frame) backgroundColor = Colors.clear } required init?(coder: NSCoder) { super.init(coder: coder) } func addOval() { layer.addSublayer(ovalLayer) ovalLayer.expand() NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "wobbleOval", userInfo: nil, repeats: false) } func wobbleOval() { ovalLayer.wobble() // 1 layer.addSublayer(triangleLayer) // Add this line ovalLayer.wobble() // 2 // Add the code below NSTimer.scheduledTimerWithTimeInterval(0.9, target: self, selector: "drawAnimatedTriangle", userInfo: nil, repeats: false) } func drawAnimatedTriangle() { triangleLayer.animate() NSTimer.scheduledTimerWithTimeInterval(0.9, target: self, selector: "spinAndTransform", userInfo: nil, repeats: false) } func spinAndTransform() { // 1 layer.anchorPoint = CGPointMake(0.5, 0.6) // 2 let rotationAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnimation.toValue = CGFloat(M_PI * 2.0) rotationAnimation.duration = 0.45 rotationAnimation.removedOnCompletion = true layer.addAnimation(rotationAnimation, forKey: nil) // 3 ovalLayer.contract() NSTimer.scheduledTimerWithTimeInterval(0.45, target: self, selector: "drawRedAnimatedRectangle", userInfo: nil, repeats: false) NSTimer.scheduledTimerWithTimeInterval(0.65, target: self, selector: "drawBlueAnimatedRectangle", userInfo: nil, repeats: false) } func drawRedAnimatedRectangle() { layer.addSublayer(redRectangleLayer) redRectangleLayer.animateStrokeWithColor(Colors.red) } func drawBlueAnimatedRectangle() { layer.addSublayer(blueRectangleLayer) blueRectangleLayer.animateStrokeWithColor(Colors.blue) NSTimer.scheduledTimerWithTimeInterval(0.40, target: self, selector: "drawArc", userInfo: nil, repeats: false) } func drawArc() { layer.addSublayer(arcLayer) arcLayer.animate() NSTimer.scheduledTimerWithTimeInterval(0.90, target: self, selector: "expandView", userInfo: nil, repeats: false) } func expandView() { backgroundColor = Colors.blue frame = CGRectMake(frame.origin.x - blueRectangleLayer.lineWidth, frame.origin.y - blueRectangleLayer.lineWidth, frame.size.width + blueRectangleLayer.lineWidth * 2, frame.size.height + blueRectangleLayer.lineWidth * 2) layer.sublayers = nil UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.frame = self.parentFrame }, completion: { finished in self.addLabel() }) } func addLabel() { delegate?.animateLabel() } }
17ee17918d5946ab684753ee344d1ab0
26.38843
109
0.704888
false
false
false
false
ChrisAU/PapyrusCore
refs/heads/master
PapyrusCoreTests/AnagramDictionary.swift
bsd-2-clause
1
// // AnagramDictionary.swift // AnagramDictionary // // Created by Chris Nevin on 27/05/2016. // Copyright © 2016 CJNevin. All rights reserved. // import Foundation import PapyrusCore internal func hashValue(_ word: String) -> String { return String(word.characters.sorted()) } internal func hashValue(_ characters: [Character]) -> String { return String(characters.sorted()) } public struct AnagramDictionary: Lookup { private let words: Words public subscript(letters: [Character]) -> Anagrams? { return words[hashValue(letters)] } public func lookup(word: String) -> Bool { return self[hashValue(word)]?.contains(word) ?? false } public static func deserialize(_ data: Data) -> AnagramDictionary? { guard let words = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Words else { return nil } return AnagramDictionary(words: words) } public static func load(_ path: String) -> AnagramDictionary? { guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return nil } return AnagramDictionary.deserialize(data) } public init?(filename: String, type: String = "bin", bundle: Bundle = .main) { guard let anagramPath = bundle.path(forResource: filename, ofType: type), let anagramDictionary = AnagramDictionary.load(anagramPath) else { return nil } self = anagramDictionary } init(words: Words) { self.words = words } } public class AnagramBuilder { private var words = Words() public func addWord(_ word: String) { let hash = hashValue(word) var existing = words[hash] ?? [] existing.append(word) words[hash] = existing } public func serialize() -> Data { return try! JSONSerialization.data(withJSONObject: words, options: JSONSerialization.WritingOptions(rawValue: 0)) } }
eb4c3c6dbaf096656bbee2bd75c68334
27.452055
146
0.635532
false
false
false
false
JamieScanlon/AugmentKit
refs/heads/master
AugmentKit/AKCore/Targets/GazeTarget.swift
mit
1
// // AKGazeTarget.swift // AugmentKit // // MIT License // // Copyright (c) 2018 JamieScanlon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import simd import ModelIO /** An ARTarget object whos vector matches the rotation of the device */ open class GazeTarget: AKTarget { /** A direction vector relative to it's position and can be a unit vector. Matches the orientation of the device */ public var vectorDirection: AKVector /** A type string. Always returns "GazeTarget" */ public static var type: String { return "GazeTarget" } /** The `MDLAsset` associated with the entity. */ public var asset: MDLAsset /** A unique, per-instance identifier */ public var identifier: UUID? /** An array of `AKEffect` objects that are applied by the renderer */ public var effects: [AnyEffect<Any>]? /** Specified a perfered renderer to use when rendering this enitity. Most will use the standard PBR renderer but some entities may prefer a simpiler renderer when they are not trying to achieve the look of real-world objects. Defaults to `ShaderPreference.simple` */ public var shaderPreference: ShaderPreference = .simple /** Indicates whether this geometry participates in the generation of augmented shadows. Defaults to `false`. */ public var generatesShadows: Bool = false /** If `true`, the current base color texture of the entity has changed since the last time it was rendered and the pixel data needs to be updated. This flag can be used to achieve dynamically updated textures for rendered objects. */ public var needsColorTextureUpdate: Bool = false /// If `true` the underlying mesh for this geometry has changed and the renderer needs to update. This can be used to achieve dynamically generated geometries that change over time. public var needsMeshUpdate: Bool = false /** The position of the tracker. The position is relative to the user. */ public var position: AKRelativePosition /** Initializes a new object with an `MDLAsset` and transform that represents a position relative to the current uses position. - Parameters: - withModelAsset: The `MDLAsset` associated with the entity. - withUserRelativeTransform: A transform used to create a `AKRelativePosition` */ public init(withModelAsset asset: MDLAsset, withUserRelativeTransform relativeTransform: matrix_float4x4) { self.asset = asset let myPosition = AKRelativePosition(withTransform: relativeTransform, relativeTo: UserPosition()) self.position = myPosition self.vectorDirection = AKVector(x: 0, y: 0, z: -1) } } extension GazeTarget: CustomStringConvertible, CustomDebugStringConvertible { /// :nodoc: public var description: String { return debugDescription } /// :nodoc: public var debugDescription: String { let myDescription = "<GazeTarget: \(Unmanaged.passUnretained(self).toOpaque())> type: \(GazeTarget.type), identifier: \(identifier?.debugDescription ?? "None"), vectorDirection: \(vectorDirection), position: \(position), asset: \(asset), effects: \(effects.debugDescription), shaderPreference: \(shaderPreference), generatesShadows: \(generatesShadows)" return myDescription } }
1feb5863f88b3020b7f6cda3bf554bdb
42.607843
361
0.715603
false
false
false
false
faimin/ZDOpenSourceDemo
refs/heads/master
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/NodeProperties/NodeProperty.swift
mit
1
// // NodeProperty.swift // lottie-swift // // Created by Brandon Withrow on 1/30/19. // import Foundation import CoreGraphics /// A node property that holds a reference to a T ValueProvider and a T ValueContainer. class NodeProperty<T>: AnyNodeProperty { var valueType: Any.Type { return T.self } var value: T { return typedContainer.outputValue } var valueContainer: AnyValueContainer { return typedContainer } var valueProvider: AnyValueProvider init(provider: AnyValueProvider) { self.valueProvider = provider self.typedContainer = ValueContainer<T>(provider.value(frame: 0) as! T) self.typedContainer.setNeedsUpdate() } func needsUpdate(frame: CGFloat) -> Bool { return valueContainer.needsUpdate || valueProvider.hasUpdate(frame: frame) } func setProvider(provider: AnyValueProvider) { guard provider.valueType == valueType else { return } self.valueProvider = provider valueContainer.setNeedsUpdate() } func update(frame: CGFloat) { typedContainer.setValue(valueProvider.value(frame: frame), forFrame: frame) } fileprivate var typedContainer: ValueContainer<T> }
6c136592aecdc467848f02129fbeec42
23.93617
87
0.720137
false
false
false
false
apple/swift-nio-ssl
refs/heads/main
Sources/NIOSSL/SSLErrors.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// @_implementationOnly import CNIOBoringSSL import NIOCore /// Wraps a single error from BoringSSL. public struct BoringSSLInternalError: Equatable, CustomStringConvertible, Sendable { private enum Backing: Hashable { case boringSSLErrorInfo(UInt32, String, UInt) case synthetic(String) } private var backing: Backing private var errorMessage: String? { switch self.backing { case .boringSSLErrorInfo(let errorCode, let filepath, let line): // TODO(cory): This should become non-optional in the future, as it always succeeds. var scratchBuffer = [CChar](repeating: 0, count: 512) return scratchBuffer.withUnsafeMutableBufferPointer { pointer in CNIOBoringSSL_ERR_error_string_n(errorCode, pointer.baseAddress!, pointer.count) let errorString = String(cString: pointer.baseAddress!) return "\(errorString) at \(filepath):\(line)" } case .synthetic(let description): return description } } private var errorCode: String { switch self.backing { case .boringSSLErrorInfo(let code, _, _): return String(code, radix: 10) case .synthetic: return "" } } public var description: String { return "Error: \(errorCode) \(errorMessage ?? "")" } init(errorCode: UInt32, filename: String, line: UInt) { self.backing = .boringSSLErrorInfo(errorCode, filename, line) } private init(syntheticErrorDescription description: String) { self.backing = .synthetic(description) } /// Received EOF during the TLS handshake. public static let eofDuringHandshake = Self(syntheticErrorDescription: "EOF during handshake") /// Received EOF during additional certificate chain verification. public static let eofDuringAdditionalCertficiateChainValidation = Self(syntheticErrorDescription: "EOF during addition certificate chain validation") } /// A representation of BoringSSL's internal error stack: a list of BoringSSL errors. public typealias NIOBoringSSLErrorStack = [BoringSSLInternalError] /// Errors that can be raised by NIO's BoringSSL wrapper. public enum NIOSSLError: Error { case writeDuringTLSShutdown @available(*, deprecated, message: "unableToAllocateBoringSSLObject can no longer be thrown") case unableToAllocateBoringSSLObject case noSuchFilesystemObject case failedToLoadCertificate case failedToLoadPrivateKey case handshakeFailed(BoringSSLError) case shutdownFailed(BoringSSLError) case cannotMatchULabel case noCertificateToValidate case unableToValidateCertificate case cannotFindPeerIP case readInInvalidTLSState case uncleanShutdown } extension NIOSSLError: Equatable {} /// Closing the TLS channel cleanly timed out, so it was closed uncleanly. public struct NIOSSLCloseTimedOutError: Error {} /// An enum that wraps individual BoringSSL errors directly. public enum BoringSSLError: Error { case noError case zeroReturn case wantRead case wantWrite case wantConnect case wantAccept case wantX509Lookup case wantCertificateVerify case syscallError case sslError(NIOBoringSSLErrorStack) case unknownError(NIOBoringSSLErrorStack) case invalidSNIName(NIOBoringSSLErrorStack) case failedToSetALPN(NIOBoringSSLErrorStack) } extension BoringSSLError: Equatable {} internal extension BoringSSLError { static func fromSSLGetErrorResult(_ result: CInt) -> BoringSSLError? { switch result { case SSL_ERROR_NONE: return .noError case SSL_ERROR_ZERO_RETURN: return .zeroReturn case SSL_ERROR_WANT_READ: return .wantRead case SSL_ERROR_WANT_WRITE: return .wantWrite case SSL_ERROR_WANT_CONNECT: return .wantConnect case SSL_ERROR_WANT_ACCEPT: return .wantAccept case SSL_ERROR_WANT_CERTIFICATE_VERIFY: return .wantCertificateVerify case SSL_ERROR_WANT_X509_LOOKUP: return .wantX509Lookup case SSL_ERROR_SYSCALL: return .syscallError case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION: // This is a terrible hack: we can't add cases to this enum, so we can't represent // this directly. In all cases this should be the same as wantCertificateVerify, so we'll just use that. return .wantCertificateVerify case SSL_ERROR_SSL: return .sslError(buildErrorStack()) default: return .unknownError(buildErrorStack()) } } static func buildErrorStack() -> NIOBoringSSLErrorStack { var errorStack = NIOBoringSSLErrorStack() while true { var file: UnsafePointer<CChar>? = nil var line: CInt = 0 let errorCode = CNIOBoringSSL_ERR_get_error_line(&file, &line) if errorCode == 0 { break } let fileAsString = String(cString: file!) errorStack.append(BoringSSLInternalError(errorCode: errorCode, filename: fileAsString, line: UInt(line))) } return errorStack } } /// Represents errors that may occur while attempting to unwrap TLS from a connection. public enum NIOTLSUnwrappingError: Error { /// The TLS channel has already been closed, so it is not possible to unwrap it. case alreadyClosed /// The internal state of the handler is not able to process the unwrapping request. case invalidInternalState /// We were unwrapping the connection, but during the unwrap process a close call /// was made. This means the connection is now closed, not unwrapped. case closeRequestedDuringUnwrap /// This write was failed because the channel was unwrapped before it was flushed. case unflushedWriteOnUnwrap } /// This structure contains errors added to NIOSSL after the original ``NIOSSLError`` enum was /// shipped. This is an extensible error object that allows us to evolve it going forward. public struct NIOSSLExtraError: Error { private var baseError: NIOSSLExtraError.BaseError private var _description: String? private init(baseError: NIOSSLExtraError.BaseError, description: String?) { self.baseError = baseError self._description = description } } extension NIOSSLExtraError { private enum BaseError: Equatable { case failedToValidateHostname case serverHostnameImpossibleToMatch case cannotUseIPAddressInSNI case invalidSNIHostname } } extension NIOSSLExtraError { /// NIOSSL was unable to validate the hostname presented by the remote peer. public static let failedToValidateHostname = NIOSSLExtraError(baseError: .failedToValidateHostname, description: nil) /// The server hostname provided by the user cannot match any names in the certificate due to containing invalid characters. public static let serverHostnameImpossibleToMatch = NIOSSLExtraError(baseError: .serverHostnameImpossibleToMatch, description: nil) /// IP addresses may not be used in SNI. public static let cannotUseIPAddressInSNI = NIOSSLExtraError(baseError: .cannotUseIPAddressInSNI, description: nil) /// The SNI hostname requirements have not been met. /// /// - note: Should the provided SNI hostname be an IP address instead, ``cannotUseIPAddressInSNI`` is thrown instead /// of this error. /// /// Reasons a hostname might not meet the requirements: /// - hostname in UTF8 is more than 255 bytes /// - hostname is the empty string /// - hostname contains the `0` unicode scalar (which would be encoded as the `0` byte which is unsupported). public static let invalidSNIHostname = NIOSSLExtraError(baseError: .invalidSNIHostname, description: nil) @inline(never) internal static func failedToValidateHostname(expectedName: String) -> NIOSSLExtraError { let description = "Couldn't find \(expectedName) in certificate from peer" return NIOSSLExtraError(baseError: .failedToValidateHostname, description: description) } @inline(never) internal static func serverHostnameImpossibleToMatch(hostname: String) -> NIOSSLExtraError { let description = "The server hostname \(hostname) cannot be matched due to containing non-DNS characters" return NIOSSLExtraError(baseError: .serverHostnameImpossibleToMatch, description: description) } @inline(never) internal static func cannotUseIPAddressInSNI(ipAddress: String) -> NIOSSLExtraError { let description = "IP addresses cannot validly be used for Server Name Indication, got \(ipAddress)" return NIOSSLExtraError(baseError: .cannotUseIPAddressInSNI, description: description) } } extension NIOSSLExtraError: CustomStringConvertible { public var description: String { let formattedDescription = self._description.map { ": " + $0 } ?? "" return "NIOSSLExtraError.\(String(describing: self.baseError))\(formattedDescription)" } } extension NIOSSLExtraError: Equatable { public static func ==(lhs: NIOSSLExtraError, rhs: NIOSSLExtraError) -> Bool { return lhs.baseError == rhs.baseError } }
b2be884ff005e892d179075a3ea33189
37.147287
153
0.693253
false
false
false
false
jwfriese/FrequentFlyer
refs/heads/master
FrequentFlyer/AppRouting/InfoService.swift
apache-2.0
1
import struct Foundation.URLRequest import struct Foundation.URL import class Foundation.NSError import RxSwift class InfoService { var httpClient = HTTPClient() var infoDeserializer = InfoDeserializer() func getInfo(forConcourseWithURL concourseURL: String) -> Observable<Info> { guard let url = URL(string: concourseURL + "/api/v1/info") else { Logger.logError( InitializationError.serviceURL(functionName: #function, data: ["concourseURL" : concourseURL] ) ) return Observable.empty() } var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "GET" return httpClient.perform(request: request) .catchError { error in if (error as NSError).code == -1200 && (error as NSError).domain == "NSURLErrorDomain" { throw HTTPError.sslValidation } throw error } .map { return $0.body! } .flatMap { self.infoDeserializer.deserialize($0) } } }
5506474db8cb58cf30890d8e1d1a2575
32.378378
104
0.566802
false
false
false
false
DJBCompany/DHNote
refs/heads/master
NoteBook/NoteBook/HZMainTabBarController.swift
mit
1
// // HZMainTabBarController.swift // NoteBook // // Created by chris on 16/4/27. // Copyright © 2016年 chris. All rights reserved. // import UIKit class HZMainTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() let bar = HZTabBar() setValue(bar, forKey: "tabBar") addAllChildControllers() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } ///添加所有的子控制器的方法 func addAllChildControllers(){ let categoryVc = HZCategoryController(); addChildViewController(categoryVc, title: "Category", image: "") let reachVc = HZReachController() addChildViewController(reachVc, title: "Reach", image: "") let analysisVc = HZAnalysisController() addChildViewController(analysisVc, title: "Analysis", image: "") let meVc = HZAboutMeController() addChildViewController(meVc, title: "me", image: "") } ///添加子控制器 func addChildViewController(childController: UIViewController, title:String, image:String) { let nav = HZMainNavController(rootViewController: childController) navigationItem.title = title addChildViewController(nav); } }
854b8defdd2b3fcc0f580b2dca5e4dda
25.018868
96
0.637418
false
false
false
false
xNekOIx/StoryboardStyles
refs/heads/master
MyPlayground.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
mit
1
import Foundation import XCPlayground //XCPlaygroundPage.currentPage.needsIndefiniteExecution = true class StoryboardParser: NSObject, NSXMLParserDelegate { // MARK: - NSXMLParserDelegate func parserDidStartDocument(parser: NSXMLParser) { print("did start") } func parserDidEndDocument(parser: NSXMLParser) { print("did end") // process.shouldExit = true } // func parser(parser: NSXMLParser, // foundAttributeDeclarationWithName attributeName: String, // forElement elementName: String, // type: String?, // defaultValue: String?) { // print("attr: \(attributeName)\nelem: \(elementName)") // } // // func parser(parser: NSXMLParser, foundCharacters string: String) { // print(string) // } // // func parser(parser: NSXMLParser, foundElementDeclarationWithName elementName: String, model: String) { // print(elementName) // } // func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { print("element: \(elementName)\nattrs: \(attributeDict)") } func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { print("parseError: \n\(parseError)") // process.shouldExit = true } func parser(parser: NSXMLParser, validationErrorOccurred validationError: NSError) { print("validationError: \n\(validationError)") // process.shouldExit = true } } let storyboardData = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + "<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"9059\" systemVersion=\"15B42\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" useTraitCollections=\"YES\">" + "<dependencies>" + "<plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"9049\"/>" + "</dependencies>" + "<scenes>" + "<!--View Controller-->" + "<scene sceneID=\"X5B-PV-zIh\">" + "<objects>" + "<viewController id=\"iHD-XU-1t3\" sceneMemberID=\"viewController\">" + "<layoutGuides>" + "<viewControllerLayoutGuide type=\"top\" id=\"vBi-pL-j8v\"/>" + "<viewControllerLayoutGuide type=\"bottom\" id=\"YIc-tN-jzC\"/>" + "</layoutGuides>" + "<view key=\"view\" contentMode=\"scaleToFill\" id=\"D67-Go-AuY\">" + "<rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"600\" height=\"600\"/>" + "<autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>" + "<animations/>" + "<color key=\"backgroundColor\" white=\"1\" alpha=\"1\" colorSpace=\"calibratedWhite\"/>" + "<userDefinedRuntimeAttributes>" + "<userDefinedRuntimeAttribute type=\"string\" keyPath=\"styleClass\" value=\"PewPew\"/>" + "</userDefinedRuntimeAttributes>" + "</view>" + "</viewController>" + "<placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"wG4-Wr-g0G\" userLabel=\"First Responder\" sceneMemberID=\"firstResponder\"/>" + "</objects>" + "<point key=\"canvasLocation\" x=\"977\" y=\"394\"/>" + "</scene>" + "</scenes>" + "</document>").dataUsingEncoding(NSUTF8StringEncoding) let sParser = StoryboardParser() let parser = NSXMLParser(data: storyboardData!) parser.delegate = sParser parser.parse() print(parser.parserError)
5b77da3ab6e526c2f033863746d7147a
37.370787
253
0.662665
false
false
false
false
gmilos/swift
refs/heads/master
test/SILGen/properties.swift
apache-2.0
2
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s var zero: Int = 0 func use(_: Int) {} func use(_: Double) {} func getInt() -> Int { return zero } // CHECK-LABEL: sil hidden @{{.*}}physical_tuple_lvalue // CHECK: bb0(%0 : $Int): func physical_tuple_lvalue(_ c: Int) { var x : (Int, Int) // CHECK: [[BOX:%[0-9]+]] = alloc_box ${ var (Int, Int) } // CHECK: [[XADDR1:%.*]] = project_box [[BOX]] // CHECK: [[XADDR:%[0-9]+]] = mark_uninitialized [var] [[XADDR1]] x.1 = c // CHECK: [[X_1:%[0-9]+]] = tuple_element_addr [[XADDR]] : {{.*}}, 1 // CHECK: assign %0 to [[X_1]] } func tuple_rvalue() -> (Int, Int) {} // CHECK-LABEL: sil hidden @{{.*}}physical_tuple_rvalue func physical_tuple_rvalue() -> Int { return tuple_rvalue().1 // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF10properties12tuple_rvalue // CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]]() // CHECK: [[RET:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 1 // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_TF10properties16tuple_assignment func tuple_assignment(_ a: inout Int, b: inout Int) { // CHECK: bb0([[A_ADDR:%[0-9]+]] : $*Int, [[B_ADDR:%[0-9]+]] : $*Int): // CHECK: [[B:%[0-9]+]] = load [trivial] [[B_ADDR]] // CHECK: [[A:%[0-9]+]] = load [trivial] [[A_ADDR]] // CHECK: assign [[B]] to [[A_ADDR]] // CHECK: assign [[A]] to [[B_ADDR]] (a, b) = (b, a) } // CHECK-LABEL: sil hidden @_TF10properties18tuple_assignment_2 func tuple_assignment_2(_ a: inout Int, b: inout Int, xy: (Int, Int)) { // CHECK: bb0([[A_ADDR:%[0-9]+]] : $*Int, [[B_ADDR:%[0-9]+]] : $*Int, [[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int): (a, b) = xy // CHECK: [[XY2:%[0-9]+]] = tuple ([[X]] : $Int, [[Y]] : $Int) // CHECK: [[X:%[0-9]+]] = tuple_extract [[XY2]] : {{.*}}, 0 // CHECK: [[Y:%[0-9]+]] = tuple_extract [[XY2]] : {{.*}}, 1 // CHECK: assign [[X]] to [[A_ADDR]] // CHECK: assign [[Y]] to [[B_ADDR]] } class Ref { var x, y : Int var ref : Ref var z: Int { get {} set {} } var val_prop: Val { get {} set {} } subscript(i: Int) -> Float { get {} set {} } init(i: Int) { x = i y = i ref = self } } class RefSubclass : Ref { var w : Int override init (i: Int) { w = i super.init(i: i) } } struct Val { var x, y : Int var ref : Ref var z: Int { get {} set {} } var z_tuple: (Int, Int) { get {} set {} } subscript(i: Int) -> Float { get {} set {} } } // CHECK-LABEL: sil hidden @_TF10properties22physical_struct_lvalue func physical_struct_lvalue(_ c: Int) { var v : Val // CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var Val } v.y = c // CHECK: assign %0 to [[X_1]] } // CHECK-LABEL: sil hidden @_TF10properties21physical_class_lvalue func physical_class_lvalue(_ r: Ref, a: Int) { r.y = a // CHECK: [[FN:%[0-9]+]] = class_method %0 : $Ref, #Ref.y!setter.1 // CHECK: apply [[FN]](%1, %0) : $@convention(method) (Int, @guaranteed Ref) -> () // CHECK: destroy_value %0 : $Ref } // CHECK-LABEL: sil hidden @_TF10properties24physical_subclass_lvalue func physical_subclass_lvalue(_ r: RefSubclass, a: Int) { // CHECK: bb0([[ARG1:%.*]] : $RefSubclass, [[ARG2:%.*]] : $Int): r.y = a // CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]] : $RefSubclass // CHECK: [[R_SUP:%[0-9]+]] = upcast [[ARG1_COPY]] : $RefSubclass to $Ref // CHECK: [[FN:%[0-9]+]] = class_method [[R_SUP]] : $Ref, #Ref.y!setter.1 : (Ref) -> (Int) -> () , $@convention(method) (Int, @guaranteed Ref) -> () // CHECK: apply [[FN]]([[ARG2]], [[R_SUP]]) : // CHECK: destroy_value [[R_SUP]] r.w = a // CHECK: [[FN:%[0-9]+]] = class_method [[ARG1]] : $RefSubclass, #RefSubclass.w!setter.1 // CHECK: apply [[FN]](%1, [[ARG1]]) : $@convention(method) (Int, @guaranteed RefSubclass) -> () // CHECK: destroy_value [[ARG1]] } func struct_rvalue() -> Val {} // CHECK-LABEL: sil hidden @_TF10properties22physical_struct_rvalue func physical_struct_rvalue() -> Int { return struct_rvalue().y // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF10properties13struct_rvalueFT_VS_3Val // CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]() // CHECK: [[RET:%[0-9]+]] = struct_extract [[STRUCT]] : $Val, #Val.y // CHECK: return [[RET]] } func class_rvalue() -> Ref {} // CHECK-LABEL: sil hidden @_TF10properties21physical_class_rvalue func physical_class_rvalue() -> Int { return class_rvalue().y // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF10properties12class_rvalueFT_CS_3Ref // CHECK: [[CLASS:%[0-9]+]] = apply [[FUNC]]() // CHECK: [[FN:%[0-9]+]] = class_method [[CLASS]] : $Ref, #Ref.y!getter.1 // CHECK: [[RET:%[0-9]+]] = apply [[FN]]([[CLASS]]) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_TF10properties18logical_struct_get func logical_struct_get() -> Int { return struct_rvalue().z // CHECK: [[GET_RVAL:%[0-9]+]] = function_ref @_TF10properties13struct_rvalue // CHECK: [[STRUCT:%[0-9]+]] = apply [[GET_RVAL]]() // CHECK: [[GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Valg1z // CHECK: [[VALUE:%[0-9]+]] = apply [[GET_METHOD]]([[STRUCT]]) // CHECK: return [[VALUE]] } // CHECK-LABEL: sil hidden @_TF10properties18logical_struct_set func logical_struct_set(_ value: inout Val, z: Int) { // CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z:%[0-9]+]] : $Int): value.z = z // CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals1z // CHECK: apply [[Z_SET_METHOD]]([[Z]], [[VAL]]) // CHECK: return } // CHECK-LABEL: sil hidden @_TF10properties27logical_struct_in_tuple_set func logical_struct_in_tuple_set(_ value: inout (Int, Val), z: Int) { // CHECK: bb0([[VAL:%[0-9]+]] : $*(Int, Val), [[Z:%[0-9]+]] : $Int): value.1.z = z // CHECK: [[VAL_1:%[0-9]+]] = tuple_element_addr [[VAL]] : {{.*}}, 1 // CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals1z // CHECK: apply [[Z_SET_METHOD]]([[Z]], [[VAL_1]]) // CHECK: return } // CHECK-LABEL: sil hidden @_TF10properties29logical_struct_in_reftype_set func logical_struct_in_reftype_set(_ value: inout Val, z1: Int) { // CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z1:%[0-9]+]] : $Int): value.ref.val_prop.z_tuple.1 = z1 // -- val.ref // CHECK: [[VAL_REF_ADDR:%[0-9]+]] = struct_element_addr [[VAL]] : $*Val, #Val.ref // CHECK: [[VAL_REF:%[0-9]+]] = load [copy] [[VAL_REF_ADDR]] // -- getters and setters // -- val.ref.val_prop // CHECK: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[VAL_REF_VAL_PROP_TEMP:%.*]] = alloc_stack $Val // CHECK: [[T0:%.*]] = address_to_pointer [[VAL_REF_VAL_PROP_TEMP]] : $*Val to $Builtin.RawPointer // CHECK: [[MAT_VAL_PROP_METHOD:%[0-9]+]] = class_method {{.*}} : $Ref, #Ref.val_prop!materializeForSet.1 : (Ref) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) // CHECK: [[MAT_RESULT:%[0-9]+]] = apply [[MAT_VAL_PROP_METHOD]]([[T0]], [[STORAGE]], [[VAL_REF]]) // CHECK: [[T0:%.*]] = tuple_extract [[MAT_RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>), 0 // CHECK: [[OPT_CALLBACK:%.*]] = tuple_extract [[MAT_RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>), 1 // CHECK: [[T1:%[0-9]+]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Val // CHECK: [[VAL_REF_VAL_PROP_MAT:%.*]] = mark_dependence [[T1]] : $*Val on [[VAL_REF]] // CHECK: [[V_R_VP_Z_TUPLE_MAT:%[0-9]+]] = alloc_stack $(Int, Int) // CHECK: [[LD:%[0-9]+]] = load [copy] [[VAL_REF_VAL_PROP_MAT]] // -- val.ref.val_prop.z_tuple // CHECK: [[GET_Z_TUPLE_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Valg7z_tupleT // CHECK: [[A0:%.*]] = tuple_element_addr [[V_R_VP_Z_TUPLE_MAT]] : {{.*}}, 0 // CHECK: [[A1:%.*]] = tuple_element_addr [[V_R_VP_Z_TUPLE_MAT]] : {{.*}}, 1 // CHECK: [[V_R_VP_Z_TUPLE:%[0-9]+]] = apply [[GET_Z_TUPLE_METHOD]]([[LD]]) // CHECK: [[T0:%.*]] = tuple_extract [[V_R_VP_Z_TUPLE]] : {{.*}}, 0 // CHECK: [[T1:%.*]] = tuple_extract [[V_R_VP_Z_TUPLE]] : {{.*}}, 1 // CHECK: store [[T0]] to [trivial] [[A0]] // CHECK: store [[T1]] to [trivial] [[A1]] // -- write to val.ref.val_prop.z_tuple.1 // CHECK: [[V_R_VP_Z_TUPLE_1:%[0-9]+]] = tuple_element_addr [[V_R_VP_Z_TUPLE_MAT]] : {{.*}}, 1 // CHECK: assign [[Z1]] to [[V_R_VP_Z_TUPLE_1]] // -- writeback to val.ref.val_prop.z_tuple // CHECK: [[WB_V_R_VP_Z_TUPLE:%[0-9]+]] = load [trivial] [[V_R_VP_Z_TUPLE_MAT]] // CHECK: [[SET_Z_TUPLE_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals7z_tupleT // CHECK: apply [[SET_Z_TUPLE_METHOD]]({{%[0-9]+, %[0-9]+}}, [[VAL_REF_VAL_PROP_MAT]]) // -- writeback to val.ref.val_prop // CHECK: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Ref, @thick Ref.Type) -> () // CHECK: [[REF_MAT:%.*]] = alloc_stack $Ref // CHECK: store [[VAL_REF]] to [init] [[REF_MAT]] // CHECK: [[T0:%.*]] = metatype $@thick Ref.Type // CHECK: [[T1:%.*]] = address_to_pointer [[VAL_REF_VAL_PROP_MAT]] // CHECK: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[REF_MAT]], [[T0]]) // CHECK: br [[CONT]] // CHECK: [[CONT]]: // -- cleanup // CHECK: dealloc_stack [[V_R_VP_Z_TUPLE_MAT]] // CHECK: dealloc_stack [[VAL_REF_VAL_PROP_TEMP]] // -- don't need to write back to val.ref because it's a ref type } func reftype_rvalue() -> Ref {} // CHECK-LABEL: sil hidden @_TF10properties18reftype_rvalue_set func reftype_rvalue_set(_ value: Val) { reftype_rvalue().val_prop = value } // CHECK-LABEL: sil hidden @_TF10properties27tuple_in_logical_struct_set func tuple_in_logical_struct_set(_ value: inout Val, z1: Int) { // CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z1:%[0-9]+]] : $Int): value.z_tuple.1 = z1 // CHECK: [[Z_TUPLE_MATERIALIZED:%[0-9]+]] = alloc_stack $(Int, Int) // CHECK: [[VAL1:%[0-9]+]] = load [copy] [[VAL]] // CHECK: [[Z_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Valg7z_tupleT // CHECK: [[A0:%.*]] = tuple_element_addr [[Z_TUPLE_MATERIALIZED]] : {{.*}}, 0 // CHECK: [[A1:%.*]] = tuple_element_addr [[Z_TUPLE_MATERIALIZED]] : {{.*}}, 1 // CHECK: [[Z_TUPLE:%[0-9]+]] = apply [[Z_GET_METHOD]]([[VAL1]]) // CHECK: [[T0:%.*]] = tuple_extract [[Z_TUPLE]] : {{.*}}, 0 // CHECK: [[T1:%.*]] = tuple_extract [[Z_TUPLE]] : {{.*}}, 1 // CHECK: store [[T0]] to [trivial] [[A0]] // CHECK: store [[T1]] to [trivial] [[A1]] // CHECK: [[Z_TUPLE_1:%[0-9]+]] = tuple_element_addr [[Z_TUPLE_MATERIALIZED]] : {{.*}}, 1 // CHECK: assign [[Z1]] to [[Z_TUPLE_1]] // CHECK: [[Z_TUPLE_MODIFIED:%[0-9]+]] = load [trivial] [[Z_TUPLE_MATERIALIZED]] // CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals7z_tupleT // CHECK: apply [[Z_SET_METHOD]]({{%[0-9]+, %[0-9]+}}, [[VAL]]) // CHECK: dealloc_stack [[Z_TUPLE_MATERIALIZED]] // CHECK: return } var global_prop : Int { // CHECK-LABEL: sil hidden @_TF10propertiesg11global_prop get { return zero } // CHECK-LABEL: sil hidden @_TF10propertiess11global_prop set { use(newValue) } } // CHECK-LABEL: sil hidden @_TF10properties18logical_global_get func logical_global_get() -> Int { return global_prop // CHECK: [[GET:%[0-9]+]] = function_ref @_TF10propertiesg11global_prop // CHECK: [[VALUE:%[0-9]+]] = apply [[GET]]() // CHECK: return [[VALUE]] } // CHECK-LABEL: sil hidden @_TF10properties18logical_global_set func logical_global_set(_ x: Int) { global_prop = x // CHECK: [[SET:%[0-9]+]] = function_ref @_TF10propertiess11global_prop // CHECK: apply [[SET]](%0) } // CHECK-LABEL: sil hidden @_TF10properties17logical_local_get func logical_local_get(_ x: Int) -> Int { var prop : Int { get { return x } } // CHECK: [[GET_REF:%[0-9]+]] = function_ref [[PROP_GET_CLOSURE:@_TFF10properties17logical_local_get]] // CHECK: apply [[GET_REF]](%0) return prop } // CHECK-: sil shared [[PROP_GET_CLOSURE]] // CHECK: bb0(%{{[0-9]+}} : $Int): // CHECK-LABEL: sil hidden @_TF10properties26logical_local_captured_get func logical_local_captured_get(_ x: Int) -> Int { var prop : Int { get { return x } } func get_prop() -> Int { return prop } return get_prop() // CHECK: [[FUNC_REF:%[0-9]+]] = function_ref @_TFF10properties26logical_local_captured_get // CHECK: apply [[FUNC_REF]](%0) } // CHECK: sil shared @_TFF10properties26logical_local_captured_get // CHECK: bb0(%{{[0-9]+}} : $Int): func inout_arg(_ x: inout Int) {} // CHECK-LABEL: sil hidden @_TF10properties14physical_inout func physical_inout(_ x: Int) { var x = x // CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[XADDR]] inout_arg(&x) // CHECK: [[INOUT_ARG:%[0-9]+]] = function_ref @_TF10properties9inout_arg // CHECK: apply [[INOUT_ARG]]([[PB]]) } /* TODO check writeback to more complex logical prop, check that writeback * reuses temporaries */ // CHECK-LABEL: sil hidden @_TF10properties17val_subscript_get // CHECK: bb0([[VVAL:%[0-9]+]] : $Val, [[I:%[0-9]+]] : $Int): func val_subscript_get(_ v: Val, i: Int) -> Float { return v[i] // CHECK: [[SUBSCRIPT_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Valg9subscript // CHECK: [[RET:%[0-9]+]] = apply [[SUBSCRIPT_GET_METHOD]]([[I]], [[VVAL]]) : $@convention(method) (Int, @guaranteed Val) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_TF10properties17val_subscript_set // CHECK: bb0(%0 : $Val, [[I:%[0-9]+]] : $Int, [[X:%[0-9]+]] : $Float): func val_subscript_set(_ v: Val, i: Int, x: Float) { var v = v v[i] = x // CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var Val } // CHECK: [[PB:%.*]] = project_box [[VADDR]] // CHECK: [[SUBSCRIPT_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals9subscript // CHECK: apply [[SUBSCRIPT_SET_METHOD]]([[X]], [[I]], [[PB]]) } struct Generic<T> { var mono_phys:Int var mono_log: Int { get {} set {} } var typevar_member:T subscript(x: Int) -> Float { get {} set {} } subscript(x: T) -> T { get {} set {} } // CHECK-LABEL: sil hidden @_TFV10properties7Generic19copy_typevar_member mutating func copy_typevar_member(_ x: Generic<T>) { typevar_member = x.typevar_member } } // CHECK-LABEL: sil hidden @_TF10properties21generic_mono_phys_get func generic_mono_phys_get<T>(_ g: Generic<T>) -> Int { return g.mono_phys // CHECK: struct_element_addr %{{.*}}, #Generic.mono_phys } // CHECK-LABEL: sil hidden @_TF10properties20generic_mono_log_get func generic_mono_log_get<T>(_ g: Generic<T>) -> Int { return g.mono_log // CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Genericg8mono_log // CHECK: apply [[GENERIC_GET_METHOD]]< } // CHECK-LABEL: sil hidden @_TF10properties20generic_mono_log_set func generic_mono_log_set<T>(_ g: Generic<T>, x: Int) { var g = g g.mono_log = x // CHECK: [[GENERIC_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Generics8mono_log // CHECK: apply [[GENERIC_SET_METHOD]]< } // CHECK-LABEL: sil hidden @_TF10properties26generic_mono_subscript_get func generic_mono_subscript_get<T>(_ g: Generic<T>, i: Int) -> Float { return g[i] // CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Genericg9subscript // CHECK: apply [[GENERIC_GET_METHOD]]< } // CHECK-LABEL: sil hidden @{{.*}}generic_mono_subscript_set func generic_mono_subscript_set<T>(_ g: inout Generic<T>, i: Int, x: Float) { g[i] = x // CHECK: [[GENERIC_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Generics9subscript // CHECK: apply [[GENERIC_SET_METHOD]]< } // CHECK-LABEL: sil hidden @{{.*}}bound_generic_mono_phys_get func bound_generic_mono_phys_get(_ g: inout Generic<UnicodeScalar>, x: Int) -> Int { return g.mono_phys // CHECK: struct_element_addr %{{.*}}, #Generic.mono_phys } // CHECK-LABEL: sil hidden @_TF10properties26bound_generic_mono_log_get func bound_generic_mono_log_get(_ g: Generic<UnicodeScalar>, x: Int) -> Int { return g.mono_log // CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Genericg8mono_log // CHECK: apply [[GENERIC_GET_METHOD]]< } // CHECK-LABEL: sil hidden @_TF10properties22generic_subscript_type func generic_subscript_type<T>(_ g: Generic<T>, i: T, x: T) -> T { var g = g g[i] = x return g[i] } /*TODO: archetype and existential properties and subscripts */ struct StaticProperty { static var foo: Int { get { return zero } set {} } } // CHECK-LABEL: sil hidden @_TF10properties10static_get // CHECK: function_ref @_TZFV10properties14StaticPropertyg3foo{{.*}} : $@convention(method) (@thin StaticProperty.Type) -> Int func static_get() -> Int { return StaticProperty.foo } // CHECK-LABEL: sil hidden @_TF10properties10static_set // CHECK: function_ref @_TZFV10properties14StaticPropertys3foo{{.*}} : $@convention(method) (Int, @thin StaticProperty.Type) -> () func static_set(_ x: Int) { StaticProperty.foo = x } func takeInt(_ a : Int) {} protocol ForceAccessors { var a: Int { get set } } struct DidSetWillSetTests: ForceAccessors { var a: Int { willSet(newA) { // CHECK-LABEL: // {{.*}}.DidSetWillSetTests.a.willset // CHECK-NEXT: sil hidden @_TFV10properties18DidSetWillSetTestsw1a // CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: debug_value_addr %1 : $*DidSetWillSetTests takeInt(a) // CHECK-NEXT: // function_ref properties.takeInt // CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @_TF10properties7takeInt // CHECK-NEXT: [[FIELDPTR:%.*]] = struct_element_addr %1 : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: [[A:%.*]] = load [trivial] [[FIELDPTR]] : $*Int // CHECK-NEXT: apply [[TAKEINTFN]]([[A]]) : $@convention(thin) (Int) -> () takeInt(newA) // CHECK-NEXT: // function_ref properties.takeInt (Swift.Int) -> () // CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @_TF10properties7takeInt // CHECK-NEXT: apply [[TAKEINTFN]](%0) : $@convention(thin) (Int) -> () } didSet { // CHECK-LABEL: // {{.*}}.DidSetWillSetTests.a.didset // CHECK-NEXT: sil hidden @_TFV10properties18DidSetWillSetTestsW1a // CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests): // CHECK-NEXT: debug // CHECK-NEXT: debug_value_addr %1 : $*DidSetWillSetTests takeInt(a) // CHECK-NEXT: // function_ref properties.takeInt (Swift.Int) -> () // CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @_TF10properties7takeInt // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr %1 : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: [[A:%.*]] = load [trivial] [[AADDR]] : $*Int // CHECK-NEXT: apply [[TAKEINTFN]]([[A]]) : $@convention(thin) (Int) -> () a = zero // reassign, but don't infinite loop. // CHECK-NEXT: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @_TF10propertiesau4zero // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr %1 : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: copy_addr [[ZEROADDR]] to [[AADDR]] : $*Int } } init(x : Int) { // Accesses to didset/willset variables are direct in init methods and dtors. a = x a = x } // These are the synthesized getter and setter for the willset/didset variable. // CHECK-LABEL: // {{.*}}.DidSetWillSetTests.a.getter // CHECK-NEXT: sil hidden [transparent] @_TFV10properties18DidSetWillSetTestsg1aSi // CHECK: bb0(%0 : $DidSetWillSetTests): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: return %2 : $Int{{.*}} // id: %3 // CHECK-LABEL: // {{.*}}.DidSetWillSetTests.a.setter // CHECK-NEXT: sil hidden @_TFV10properties18DidSetWillSetTestss1aSi // CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: debug_value_addr %1 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr %1 : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: [[OLDVAL:%.*]] = load [trivial] [[AADDR]] : $*Int // CHECK-NEXT: debug_value [[OLDVAL]] : $Int, let, name "tmp" // CHECK-NEXT: // function_ref {{.*}}.DidSetWillSetTests.a.willset : Swift.Int // CHECK-NEXT: [[WILLSETFN:%.*]] = function_ref @_TFV10properties18DidSetWillSetTestsw1a // CHECK-NEXT: apply [[WILLSETFN]](%0, %1) : $@convention(method) (Int, @inout DidSetWillSetTests) -> () // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr %1 : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign %0 to [[AADDR]] : $*Int // CHECK-NEXT: // function_ref {{.*}}.DidSetWillSetTests.a.didset : Swift.Int // CHECK-NEXT: [[DIDSETFN:%.*]] = function_ref @_TFV10properties18DidSetWillSetTestsW1a{{.*}} : $@convention(method) (Int, @inout DidSetWillSetTests) -> () // CHECK-NEXT: apply [[DIDSETFN]]([[OLDVAL]], %1) : $@convention(method) (Int, @inout DidSetWillSetTests) -> () // CHECK-LABEL: sil hidden @_TFV10properties18DidSetWillSetTestsC // CHECK: bb0(%0 : $Int, %1 : $@thin DidSetWillSetTests.Type): // CHECK: [[SELF:%.*]] = mark_uninitialized [rootself] // CHECK: [[P1:%.*]] = struct_element_addr [[SELF]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign %0 to [[P1]] // CHECK: [[P2:%.*]] = struct_element_addr [[SELF]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign %0 to [[P2]] } // Test global observing properties. var global_observing_property : Int = zero { didSet { takeInt(global_observing_property) } } func force_global_observing_property_setter() { let x = global_observing_property global_observing_property = x } // The property is initialized with "zero". // CHECK-LABEL: sil private @globalinit_{{.*}}_func1 : $@convention(thin) () -> () { // CHECK: bb0: // CHECK-NEXT: alloc_global @_Tv10properties25global_observing_propertySi // CHECK-NEXT: %1 = global_addr @_Tv10properties25global_observing_propertySi : $*Int // CHECK: properties.zero.unsafeMutableAddressor // CHECK: return // The didSet implementation needs to call takeInt. // CHECK-LABEL: sil hidden @_TF10propertiesW25global_observing_property // CHECK: function_ref properties.takeInt // CHECK-NEXT: function_ref @_TF10properties7takeInt // The setter needs to call didSet implementation. // CHECK-LABEL: sil hidden @_TF10propertiess25global_observing_property // CHECK: function_ref properties.global_observing_property.unsafeMutableAddressor // CHECK-NEXT: function_ref @_TF10propertiesau25global_observing_property // CHECK: function_ref properties.global_observing_property.didset // CHECK-NEXT: function_ref @_TF10propertiesW25global_observing_property // Test local observing properties. func local_observing_property(_ arg: Int) { var localproperty: Int = arg { didSet { takeInt(localproperty) } } takeInt(localproperty) localproperty = arg } // This is the local_observing_property function itself. First alloc and // initialize the property to the argument value. // CHECK-LABEL: sil hidden @{{.*}}local_observing_property // CHECK: bb0([[ARG:%[0-9]+]] : $Int) // CHECK: [[BOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[BOX]] // CHECK: store [[ARG]] to [trivial] [[PB]] // <rdar://problem/16006333> observing properties don't work in @objc classes @objc class ObservingPropertyInObjCClass { var bounds: Int { willSet {} didSet {} } init(b: Int) { bounds = b } } // Superclass init methods should not get direct access to be class properties. // rdar://16151899 class rdar16151899Base { var x: Int = zero { willSet { use(x) } } } class rdar16151899Derived : rdar16151899Base { // CHECK-LABEL: sil hidden @_TFC10properties19rdar16151899Derivedc override init() { super.init() // CHECK: upcast {{.*}} : $rdar16151899Derived to $rdar16151899Base // CHECK: function_ref @_TFC10properties16rdar16151899BasecfT_S0_ : $@convention(method) (@owned rdar16151899Base) -> @owned rdar16151899Base // This should not be a direct access, it should call the setter in the // base. x = zero // CHECK: [[BASEPTR:%[0-9]+]] = upcast {{.*}} : $rdar16151899Derived to $rdar16151899Base // CHECK: load{{.*}}Int // CHECK-NEXT: [[SETTER:%[0-9]+]] = class_method {{.*}} : $rdar16151899Base, #rdar16151899Base.x!setter.1 : (rdar16151899Base) // CHECK-NEXT: apply [[SETTER]]({{.*}}, [[BASEPTR]]) } } func propertyWithDidSetTakingOldValue() { var p : Int = zero { didSet(oldValue) { // access to oldValue use(oldValue) // and newValue. use(p) } } p = zero } // CHECK: // properties.(propertyWithDidSetTakingOldValue () -> ()).(p #1).setter : Swift.Int // CHECK-NEXT: sil {{.*}} @_TFF10properties32propertyWithDidSetTakingOldValue // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : ${ var Int }): // CHECK-NEXT: debug_value [[ARG1]] : $Int, let, name "newValue", argno 1 // CHECK-NEXT: [[ARG2_PB:%.*]] = project_box [[ARG2]] // CHECK-NEXT: debug_value_addr [[ARG2_PB]] : $*Int, var, name "p", argno 2 // CHECK-NEXT: [[ARG2_PB_VAL:%.*]] = load [trivial] [[ARG2_PB]] : $*Int // CHECK-NEXT: debug_value [[ARG2_PB_VAL]] : $Int // CHECK-NEXT: assign [[ARG1]] to [[ARG2_PB]] : $*Int // CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : ${ var Int } // SEMANTIC ARC TODO: Another case where we need to put the mark_function_escape on a new projection after a copy. // CHECK-NEXT: mark_function_escape [[ARG2_PB]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FUNC:%.*]] = function_ref @_TFF10properties32propertyWithDidSetTakingOldValueFT_T_WL_1pSi : $@convention(thin) (Int, @owned { var Int }) -> () // CHECK-NEXT: %11 = apply [[FUNC]]([[ARG2_PB_VAL]], [[ARG2_COPY]]) : $@convention(thin) (Int, @owned { var Int }) -> () // CHECK-NEXT: destroy_value [[ARG2]] : ${ var Int } // CHECK-NEXT: %13 = tuple () // CHECK-NEXT: return %13 : $() // CHECK-NEXT:} // end sil function '_TFF10properties32propertyWithDidSetTakingOldValue{{.*}}' class BaseProperty { var x : Int { get {} set {} } } class DerivedProperty : BaseProperty { override var x : Int { get {} set {} } func super_property_reference() -> Int { return super.x } } // rdar://16381392 - Super property references in non-objc classes should be direct. // CHECK-LABEL: sil hidden @_TFC10properties15DerivedProperty24super_property_referencefT_Si : $@convention(method) (@guaranteed DerivedProperty) -> Int { // CHECK: bb0([[SELF:%.*]] : $DerivedProperty): // CHECK: [[SELF_COPY:%[0-9]+]] = copy_value [[SELF]] // CHECK: [[BASEPTR:%[0-9]+]] = upcast [[SELF_COPY]] : $DerivedProperty to $BaseProperty // CHECK: [[FN:%[0-9]+]] = function_ref @_TFC10properties12BasePropertyg1xSi : $@convention(method) (@guaranteed BaseProperty) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[BASEPTR]]) : $@convention(method) (@guaranteed BaseProperty) -> Int // CHECK: destroy_value [[BASEPTR]] // CHECK: return [[RESULT]] : $Int // CHECK: } // end sil function '_TFC10properties15DerivedProperty24super_property_referencefT_Si' // <rdar://problem/16411449> ownership qualifiers don't work with non-mutating struct property struct ReferenceStorageTypeRValues { unowned var p1 : Ref func testRValueUnowned() -> Ref { return p1 } // CHECK: sil hidden @{{.*}}testRValueUnowned // CHECK: bb0(%0 : $ReferenceStorageTypeRValues): // CHECK-NEXT: debug_value %0 : $ReferenceStorageTypeRValues // CHECK-NEXT: %2 = struct_extract %0 : $ReferenceStorageTypeRValues, #ReferenceStorageTypeRValues.p1 // CHECK-NEXT: strong_retain_unowned %2 : $@sil_unowned Ref // CHECK-NEXT: %4 = unowned_to_ref %2 : $@sil_unowned Ref to $Ref // CHECK-NEXT: return %4 : $Ref init() { } } // <rdar://problem/16406886> Observing properties don't work with ownership types struct ObservingPropertiesWithOwnershipTypes { unowned var alwaysPresent : Ref { didSet { } } init(res: Ref) { alwaysPresent = res } } struct ObservingPropertiesWithOwnershipTypesInferred { unowned var alwaysPresent = Ref(i: 0) { didSet { } } weak var maybePresent = nil as Ref? { willSet { } } } // <rdar://problem/16554876> property accessor synthesization of weak variables doesn't work protocol WeakPropertyProtocol { weak var maybePresent : Ref? { get set } } struct WeakPropertyStruct : WeakPropertyProtocol { weak var maybePresent : Ref? init() { maybePresent = nil } } // <rdar://problem/16629598> direct property accesses to generic struct // properties were being mischecked as computed property accesses. struct SomeGenericStruct<T> { var x: Int } // CHECK-LABEL: sil hidden @_TF10properties4getX // CHECK: struct_extract {{%.*}} : $SomeGenericStruct<T>, #SomeGenericStruct.x func getX<T>(_ g: SomeGenericStruct<T>) -> Int { return g.x } // <rdar://problem/16189360> [DF] Assert on subscript with variadic parameter struct VariadicSubscript { subscript(subs: Int...) -> Int { get { return 42 } } func test() { var s = VariadicSubscript() var x = s[0, 1, 2] } } //<rdar://problem/16620121> Initializing constructor tries to initialize computed property overridden with willSet/didSet class ObservedBase { var printInfo: Ref! } class ObservedDerived : ObservedBase { override init() {} override var printInfo: Ref! { didSet { } } } /// <rdar://problem/16953517> Class properties should be allowed in protocols, even without stored class properties protocol ProtoWithClassProp { static var x: Int { get } } class ClassWithClassProp : ProtoWithClassProp { class var x: Int { return 42 } } struct StructWithClassProp : ProtoWithClassProp { static var x: Int { return 19 } } func getX<T : ProtoWithClassProp>(_ a : T) -> Int { return T.x } func testClassPropertiesInProtocol() -> Int { return getX(ClassWithClassProp())+getX(StructWithClassProp()) } class GenericClass<T> { var x: T var y: Int final let z: T init() { fatalError("scaffold") } } // CHECK-LABEL: sil hidden @_TF10properties12genericPropsFGCS_12GenericClassSS_T_ func genericProps(_ x: GenericClass<String>) { // CHECK: class_method %0 : $GenericClass<String>, #GenericClass.x!getter.1 let _ = x.x // CHECK: class_method %0 : $GenericClass<String>, #GenericClass.y!getter.1 let _ = x.y // CHECK: [[Z:%.*]] = ref_element_addr %0 : $GenericClass<String>, #GenericClass.z // CHECK: load [copy] [[Z]] : $*String let _ = x.z } // CHECK-LABEL: sil hidden @_TF10properties28genericPropsInGenericContext func genericPropsInGenericContext<U>(_ x: GenericClass<U>) { // CHECK: [[Z:%.*]] = ref_element_addr %0 : $GenericClass<U>, #GenericClass.z // CHECK: copy_addr [[Z]] {{.*}} : $*U let _ = x.z } // <rdar://problem/18275556> 'let' properties in a class should be implicitly final class ClassWithLetProperty { let p = 42 dynamic let q = 97 // We shouldn't have any dynamic dispatch within this method, just load p. func ReturnConstant() -> Int { return p } // CHECK-LABEL: sil hidden @_TFC10properties20ClassWithLetProperty14ReturnConstant // CHECK: bb0([[ARG:%.*]] : $ClassWithLetProperty): // CHECK-NEXT: debug_value // CHECK-NEXT: [[PTR:%[0-9]+]] = ref_element_addr [[ARG]] : $ClassWithLetProperty, #ClassWithLetProperty.p // CHECK-NEXT: [[VAL:%[0-9]+]] = load [trivial] [[PTR]] : $*Int // CHECK-NEXT: return [[VAL]] : $Int // This property is marked dynamic, so go through the getter, always. func ReturnDynamicConstant() -> Int { return q } // CHECK-LABEL: sil hidden @_TFC10properties20ClassWithLetProperty21ReturnDynamicConstant // CHECK: class_method [volatile] %0 : $ClassWithLetProperty, #ClassWithLetProperty.q!getter.1.foreign } // <rdar://problem/19254812> DI bug when referencing let member of a class class r19254812Base {} class r19254812Derived: r19254812Base{ let pi = 3.14159265359 init(x : ()) { use(pi) } // Accessing the "pi" property should not copy_value/release self. // CHECK-LABEL: sil hidden @_TFC10properties16r19254812Derivedc // CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [derivedself] // Initialization of the pi field: no copy_values/releases. // CHECK: [[SELF:%[0-9]+]] = load_borrow [[SELFMUI]] : $*r19254812Derived // CHECK-NEXT: [[PIPTR:%[0-9]+]] = ref_element_addr [[SELF]] : $r19254812Derived, #r19254812Derived.pi // CHECK-NEXT: assign {{.*}} to [[PIPTR]] : $*Double // CHECK-NOT: destroy_value // CHECK-NOT: copy_value // Load of the pi field: no copy_values/releases. // CHECK: [[SELF:%[0-9]+]] = load_borrow [[SELFMUI]] : $*r19254812Derived // CHECK-NEXT: [[PIPTR:%[0-9]+]] = ref_element_addr [[SELF]] : $r19254812Derived, #r19254812Derived.pi // CHECK-NEXT: {{.*}} = load [trivial] [[PIPTR]] : $*Double // CHECK: return } class RedundantSelfRetains { final var f : RedundantSelfRetains init() { f = RedundantSelfRetains() } // <rdar://problem/19275047> Extraneous copy_values/releases of self are bad func testMethod1() { f = RedundantSelfRetains() } // CHECK-LABEL: sil hidden @_TFC10properties20RedundantSelfRetains11testMethod1 // CHECK: bb0(%0 : $RedundantSelfRetains): // CHECK-NOT: copy_value // CHECK: [[FPTR:%[0-9]+]] = ref_element_addr %0 : $RedundantSelfRetains, #RedundantSelfRetains.f // CHECK-NEXT: assign {{.*}} to [[FPTR]] : $*RedundantSelfRetains // CHECK: return } class RedundantRetains { final var field = 0 } func testRedundantRetains() { let a = RedundantRetains() a.field = 4 // no copy_value/release of a necessary here. } // CHECK-LABEL: sil hidden @_TF10properties20testRedundantRetainsFT_T_ : $@convention(thin) () -> () { // CHECK: [[A:%[0-9]+]] = apply // CHECK-NOT: copy_value // CHECK: destroy_value [[A]] : $RedundantRetains // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: return struct AddressOnlyNonmutatingSet<T> { var x: T init(x: T) { self.x = x } var prop: Int { get { return 0 } nonmutating set { } } } func addressOnlyNonmutatingProperty<T>(_ x: AddressOnlyNonmutatingSet<T>) -> Int { x.prop = 0 return x.prop } // CHECK-LABEL: sil hidden @_TF10properties30addressOnlyNonmutatingProperty // CHECK: [[SET:%.*]] = function_ref @_TFV10properties25AddressOnlyNonmutatingSets4propSi // CHECK: apply [[SET]]<T>({{%.*}}, [[TMP:%[0-9]*]]) // CHECK: destroy_addr [[TMP]] // CHECK: dealloc_stack [[TMP]] // CHECK: [[GET:%.*]] = function_ref @_TFV10properties25AddressOnlyNonmutatingSetg4propSi // CHECK: apply [[GET]]<T>([[TMP:%[0-9]*]]) // CHECK: destroy_addr [[TMP]] // CHECK: dealloc_stack [[TMP]] protocol MakeAddressOnly {} struct AddressOnlyReadOnlySubscript { var x: MakeAddressOnly? subscript(z: Int) -> Int { return z } } // CHECK-LABEL: sil hidden @_TF10properties43addressOnlyReadOnlySubscriptFromMutableBase // CHECK: [[BASE:%.*]] = alloc_box ${ var AddressOnlyReadOnlySubscript } // CHECK: copy_addr [[BASE:%.*]] to [initialization] [[COPY:%.*]] : // CHECK: [[GETTER:%.*]] = function_ref @_TFV10properties28AddressOnlyReadOnlySubscriptg9subscript // CHECK: apply [[GETTER]]({{%.*}}, [[COPY]]) func addressOnlyReadOnlySubscriptFromMutableBase(_ x: Int) { var base = AddressOnlyReadOnlySubscript() _ = base[x] } /// <rdar://problem/20912019> passing unmaterialized r-value as inout argument struct MutatingGetterStruct { var write: Int { mutating get { } } // CHECK-LABEL: sil hidden @_TZFV10properties20MutatingGetterStruct4test // CHECK: [[X:%.*]] = alloc_box ${ var MutatingGetterStruct }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK: store {{.*}} to [trivial] [[PB]] : $*MutatingGetterStruct // CHECK: apply {{%.*}}([[PB]]) : $@convention(method) (@inout MutatingGetterStruct) -> Int static func test() { var x = MutatingGetterStruct() _ = x.write } } protocol ProtocolWithReadWriteSubscript { subscript(i: Int) -> Int { get set } } struct CrashWithUnnamedSubscript : ProtocolWithReadWriteSubscript { subscript(_: Int) -> Int { get { } set { } } } /// <rdar://problem/26408353> crash when overriding internal property with /// public property public class BaseClassWithInternalProperty { var x: () = () } public class DerivedClassWithPublicProperty : BaseClassWithInternalProperty { public override var x: () { didSet {} } } // CHECK-LABEL: sil hidden @_TFC10properties29BaseClassWithInternalPropertyg1xT_ // CHECK-LABEL: sil @_TFC10properties30DerivedClassWithPublicPropertyg1xT_ // CHECK: bb0([[SELF:%.*]] : $DerivedClassWithPublicProperty): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $DerivedClassWithPublicProperty // CHECK-NEXT: [[SUPER:%.*]] = upcast [[SELF_COPY]] : $DerivedClassWithPublicProperty to $BaseClassWithInternalProperty // CHECK: [[GETTER:%.*]] = function_ref @_TFC10properties29BaseClassWithInternalPropertyg1xT_ // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SUPER]]) : $@convention(method) (@guaranteed BaseClassWithInternalProperty) -> () // CHECK-NEXT: destroy_value [[SUPER]] : $BaseClassWithInternalProperty // CHECK: } // end sil function '_TFC10properties30DerivedClassWithPublicPropertyg1xT_'
d543754a74b9741c347d220599928e33
35.276982
217
0.627929
false
false
false
false
anzfactory/QiitaCollection
refs/heads/master
QiitaCollection/UserDataManager.swift
mit
1
// // UserDataManager.swift // QiitaCollection // // Created by ANZ on 2015/02/21. // Copyright (c) 2015年 anz. All rights reserved. // import Foundation class UserDataManager { // シングルトンパターン class var sharedInstance : UserDataManager { struct Static { static let instance : UserDataManager = UserDataManager() } return Static.instance } // MARK: プロパティ let ud : NSUserDefaults = NSUserDefaults.standardUserDefaults() enum UDKeys: String { case MuteUsers = "ud-key-mute-users", Queries = "ud-key-queries", Pins = "ud-key-pins", EntryFiles = "ud-key-entry-files", DisplayedGuides = "ud-key-displayed-guide", QiitaAccessToken = "ud-key-qiita-access-token", QiitaAuthenticatedUserID = "ud-key-qiita-authenticated-user-id", GridCoverImage = "ud-key-grid-cover-image", ViewCoverImage = "ud-key-view-cover-image" } // ミュートユーザーのID var muteUsers: [String] = [String]() // 保存した検索クエリ var queries: [[String: String]] = [[String: String]]() // クリップしたもの var pins: [[String: String]] = [[String: String]]() // 保存したもの var entryFiles: [[String: String]] = [[String: String]]() // 表示したガイド var displayedGuides: [Int] = [Int]() // Qiita AccessToken var qiitaAccessToken: String = "" { didSet { if self.qiitaAccessToken.isEmpty { return } self.saveAuth() // 即時保存させる } } // Qiita AuthenticatedUser ID var qiitaAuthenticatedUserID: String = "" { didSet { if self.qiitaAuthenticatedUserID.isEmpty { return } self.saveAuth() // 即時保存させる } } var imageDataForGridCover: NSData? = nil var imageDataForViewCover: NSData? = nil // MARK: ライフサイクル init() { var defaults = [ UDKeys.MuteUsers.rawValue : self.muteUsers, UDKeys.Queries.rawValue : self.queries, UDKeys.Pins.rawValue : self.pins, UDKeys.EntryFiles.rawValue : self.entryFiles, UDKeys.DisplayedGuides.rawValue : self.displayedGuides, UDKeys.QiitaAccessToken.rawValue : self.qiitaAccessToken, UDKeys.QiitaAuthenticatedUserID.rawValue: self.qiitaAuthenticatedUserID ] self.ud.registerDefaults(defaults as [NSObject : AnyObject]) self.muteUsers = self.ud.arrayForKey(UDKeys.MuteUsers.rawValue) as! [String] self.queries = self.ud.arrayForKey(UDKeys.Queries.rawValue) as! [[String: String]] self.pins = self.ud.arrayForKey(UDKeys.Pins.rawValue) as! [[String: String]] self.entryFiles = self.ud.arrayForKey(UDKeys.EntryFiles.rawValue) as! [[String: String]] self.displayedGuides = self.ud.arrayForKey(UDKeys.DisplayedGuides.rawValue) as! [Int] self.qiitaAccessToken = self.ud.stringForKey(UDKeys.QiitaAccessToken.rawValue)! self.qiitaAuthenticatedUserID = self.ud.stringForKey(UDKeys.QiitaAuthenticatedUserID.rawValue)! self.imageDataForGridCover = self.ud.dataForKey(UDKeys.GridCoverImage.rawValue) self.imageDataForViewCover = self.ud.dataForKey(UDKeys.ViewCoverImage.rawValue) } // MARK: メソッド func saveAuth() { self.ud.setObject(self.qiitaAccessToken, forKey: UDKeys.QiitaAccessToken.rawValue) self.ud.setObject(self.qiitaAuthenticatedUserID, forKey: UDKeys.QiitaAuthenticatedUserID.rawValue) self.ud.synchronize() } func saveAll() { // プロパティで保持していたのをudへ書き込む self.ud.setObject(self.muteUsers, forKey: UDKeys.MuteUsers.rawValue) self.ud.setObject(self.queries, forKey: UDKeys.Queries.rawValue) self.ud.setObject(self.pins, forKey: UDKeys.Pins.rawValue) self.ud.setObject(self.entryFiles, forKey: UDKeys.EntryFiles.rawValue) self.ud.setObject(self.displayedGuides, forKey: UDKeys.DisplayedGuides.rawValue) self.ud.setObject(self.qiitaAccessToken, forKey: UDKeys.QiitaAccessToken.rawValue) self.ud.setObject(self.qiitaAuthenticatedUserID, forKey: UDKeys.QiitaAuthenticatedUserID.rawValue) self.ud.setObject(self.imageDataForGridCover, forKey: UDKeys.GridCoverImage.rawValue) self.ud.setObject(self.imageDataForViewCover, forKey: UDKeys.ViewCoverImage.rawValue) self.ud.synchronize() } func appendMuteUserId(userId: String) -> Bool { if self.isMutedUser(userId) { return false } self.muteUsers.append(userId) return true } func isMutedUser(userId: String) -> Bool { return contains(self.muteUsers, userId) } func clearMutedUser(userId: String) -> [String] { if !isMutedUser(userId) { return self.muteUsers } self.muteUsers.removeObject(userId) return self.muteUsers } func appendQuery(query: String, label: String) { let index = self.indexItem(self.queries, target: query, id: "query") if index != NSNotFound { return } self.queries.append([ "query": query, "title": label ]) } func clearQuery(query: String) { let index = self.indexItem(self.queries, target: query, id: "query") if index == NSNotFound { return } self.queries.removeAtIndex(index) } func clearQuery(index: Int) { if index >= self.queries.count { return } self.queries.removeAtIndex(index) } func appendPinEntry(entryId: String, entryTitle: String) { if self.pins.count >= 10 { self.pins.removeAtIndex(0) } else if self.hasPinEntry(entryId) != NSNotFound { // 重複ID return } self.pins.append([ "id" : entryId, "title": entryTitle ]) } func hasPinEntry(entryId: String) -> Int { return self.indexItem(self.pins, target: entryId) } func clearPinEntry(index: Int) -> [[String: String]] { self.pins.removeAtIndex(index) return self.pins } func clearPinEntry(entryId: String) -> [[String: String]] { let index: Int = self.hasPinEntry(entryId) if index == NSNotFound { return self.pins } self.pins.removeAtIndex(index) return self.pins } func titleSavedEntry(entryId: String) -> String { let index: Int = self.indexItem(self.entryFiles, target: entryId) if index == NSNotFound { return "" } let item: [String: String] = self.entryFiles[index] return item["title"]! } func hasSavedEntry(entryId: String) -> Bool { return self.indexItem(self.entryFiles, target: entryId) != NSNotFound } func appendSavedEntry(entryId: String, title:String) { if self.hasSavedEntry(entryId) { return } self.entryFiles.append([ "id" : entryId, "title" : title ]) } func removeEntry(entryId: String) { let index = self.indexItem(self.entryFiles, target: entryId) self.entryFiles.removeAtIndex(index) } func isDisplayedGuide(guide: Int) -> Bool { return contains(self.displayedGuides, guide) } func appendDisplayedGuide(guide: Int) { if self.isDisplayedGuide(guide) { return } self.displayedGuides.append(guide) } func indexItem(items: [[String: String]], target:String, id: String = "id") -> Int { for var i = 0; i < items.count; i++ { let item = items[i] if item[id] == target { return i } } return NSNotFound } func setQiitaAccessToken(token: String) { self.qiitaAccessToken = token } func clearQiitaAccessToken() { self.qiitaAccessToken = "" } func isAuthorizedQiita() -> Bool { return !self.qiitaAccessToken.isEmpty } func setImageForGridCover(image: UIImage) { self.imageDataForGridCover = UIImagePNGRepresentation(image) self.imageDataForViewCover = nil } func setImageForViewCover(image: UIImage) { self.imageDataForViewCover = UIImagePNGRepresentation(image) self.imageDataForGridCover = nil } func clearImageCover() { self.imageDataForViewCover = nil self.imageDataForGridCover = nil } func hasImageForGridCover() -> Bool { return self.imageDataForGridCover != nil } func hasImageForViewCover() -> Bool { return self.imageDataForViewCover != nil } func imageForGridCover() -> UIImage? { return UIImage(data: self.imageDataForGridCover!) } func imageForViewCover() -> UIImage? { return UIImage(data: self.imageDataForViewCover!) } }
e294c5aa0ced927d6e59e2229f3a0e5d
31.350877
106
0.599024
false
false
false
false
linchaosheng/CSSwiftWB
refs/heads/master
SwiftCSWB 3/SwiftCSWB/Class/Home/C/WBQRCodeCardViewController.swift
apache-2.0
1
// // QRCodeCardViewController.swift // DSWeibo // // Created by xiaomage on 15/9/9. // Copyright © 2015年 小码哥. All rights reserved. // import UIKit class WBQRCodeCardViewController: UIViewController { // MARK: - 懒加载 fileprivate lazy var iconView: UIImageView = UIImageView() override func viewDidLoad() { super.viewDidLoad() // 1.设置标题 navigationItem.title = "我的名片" // 2.添加图片容器 view.addSubview(iconView) // 3.布局图片容器 iconView.bounds = CGRect(x: 0, y: 0, width: 300, height: 300) iconView.center = view.center // iconView.backgroundColor = UIColor.redColor() // 4.生成二维码 let qrcodeImage = creatQRCodeImage() // 5.将生成好的二维码添加到图片容器上 iconView.image = qrcodeImage } fileprivate func creatQRCodeImage() -> UIImage{ // 1.创建滤镜 let filter = CIFilter(name: "CIQRCodeGenerator") // 2.还原滤镜的默认属性 filter?.setDefaults() // 3.设置需要生成二维码的数据 filter?.setValue("安人多梦".data(using: String.Encoding.utf8), forKey: "inputMessage") // 4.从滤镜中取出生成好的图片 let ciImage = filter?.outputImage // 创建高清二维码 let bgImage = createNonInterpolatedUIImageFormCIImage(ciImage!, size: 300) // 5.创建一个头像 let icon = UIImage(named: "avatar_vip") // 6.合成图片(将二维码和头像进行合并) let newImage = creteImage(bgImage, iconImage: icon!) // 7.返回生成好的二维码 return newImage } /** 合成图片 :param: bgImage 背景图片 :param: iconImage 头像 */ fileprivate func creteImage(_ bgImage: UIImage, iconImage: UIImage) -> UIImage { // 1.开启图片上下文 UIGraphicsBeginImageContext(bgImage.size) // 2.绘制背景图片 bgImage.draw(in: CGRect(origin: CGPoint.zero, size: bgImage.size)) // 3.绘制头像 let W : CGFloat = 50 let H : CGFloat = W let X = (bgImage.size.width - W) * 0.5 let Y = (bgImage.size.height - H) * 0.5 iconImage.draw(in: CGRect(x: X, y: Y, width: W, height: H)) // 4.取出绘制号的图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() // 5.关闭上下文 UIGraphicsEndImageContext() // 6.返回合成号的图片 return newImage! } /** 根据CIImage生成指定大小的高清UIImage :param: image 指定CIImage :param: size 指定大小 :returns: 生成好的图片 */ fileprivate func createNonInterpolatedUIImageFormCIImage(_ image: CIImage, size: CGFloat) -> UIImage { let extent: CGRect = image.extent.integral let scale: CGFloat = min(size/extent.width, size/extent.height) // 1.创建bitmap; let width = extent.width * scale let height = extent.height * scale let cs: CGColorSpace = CGColorSpaceCreateDeviceGray() let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 0)! let context = CIContext(options: nil) let bitmapImage: CGImage = context.createCGImage(image, from: extent)! bitmapRef.interpolationQuality = CGInterpolationQuality.none bitmapRef.scaleBy(x: scale, y: scale); bitmapRef.draw(bitmapImage, in: extent); // 2.保存bitmap到图片 let scaledImage: CGImage = bitmapRef.makeImage()! return UIImage(cgImage: scaledImage) } }
f8f681b3acf5611e9e3de03a531769a8
27.893443
148
0.583546
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Overlay/ActiveCallViewController.swift
gpl-3.0
1
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireSystem import WireDataModel import WireSyncEngine private let zmLog = ZMSLog(tag: "calling") protocol ActiveCallViewControllerDelegate: AnyObject { func activeCallViewControllerDidDisappear(_ activeCallViewController: ActiveCallViewController, for conversation: ZMConversation?) } /// ViewController container for CallViewControllers. Displays the active the controller for active or incoming calls. final class ActiveCallViewController: UIViewController { weak var delegate: ActiveCallViewControllerDelegate? var callStateObserverToken: Any? init(voiceChannel: VoiceChannel) { visibleVoiceChannelViewController = CallViewController(voiceChannel: voiceChannel, selfUser: ZMUser.selfUser()) super.init(nibName: nil, bundle: nil) addChild(visibleVoiceChannelViewController) visibleVoiceChannelViewController.view.frame = view.bounds visibleVoiceChannelViewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] view.addSubview(visibleVoiceChannelViewController.view) visibleVoiceChannelViewController.didMove(toParent: self) zmLog.debug(String(format: "Presenting CallViewController: %p", visibleVoiceChannelViewController)) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var visibleVoiceChannelViewController: CallViewController { didSet { transition(to: visibleVoiceChannelViewController, from: oldValue) } } override func viewDidLoad() { super.viewDidLoad() guard let userSession = ZMUserSession.shared() else { zmLog.error("UserSession not available when initializing \(type(of: self))") return } callStateObserverToken = WireCallCenterV3.addCallStateObserver(observer: self, userSession: userSession) visibleVoiceChannelViewController.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateVisibleVoiceChannelViewController() } override var childForStatusBarStyle: UIViewController? { return visibleVoiceChannelViewController } override var childForStatusBarHidden: UIViewController? { return visibleVoiceChannelViewController } func updateVisibleVoiceChannelViewController() { guard let conversation = ZMUserSession.shared()?.priorityCallConversation, visibleVoiceChannelViewController.conversation != conversation, let voiceChannel = conversation.voiceChannel else { return } visibleVoiceChannelViewController = CallViewController(voiceChannel: voiceChannel, selfUser: ZMUser.selfUser()) visibleVoiceChannelViewController.delegate = self } func transition(to toViewController: UIViewController, from fromViewController: UIViewController) { guard toViewController != fromViewController else { return } zmLog.debug(String(format: "Transitioning to CallViewController: %p from: %p", toViewController, fromViewController)) toViewController.view.frame = view.bounds toViewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] addChild(toViewController) transition(from: fromViewController, to: toViewController, duration: 0.35, options: .transitionCrossDissolve, animations: nil, completion: { _ in toViewController.didMove(toParent: self) fromViewController.removeFromParent() }) } var ongoingCallConversation: ZMConversation? { return ZMUserSession.shared()?.ongoingCallConversation } } extension ActiveCallViewController: WireCallCenterCallStateObserver { func callCenterDidChange(callState: CallState, conversation: ZMConversation, caller: UserType, timestamp: Date?, previousCallState: CallState?) { updateVisibleVoiceChannelViewController() } } extension ActiveCallViewController: CallViewControllerDelegate { func callViewControllerDidDisappear(_ callController: CallViewController, for conversation: ZMConversation?) { delegate?.activeCallViewControllerDidDisappear(self, for: conversation) } }
e0308c28327201887788c559c08a8418
36.05
149
0.717756
false
false
false
false
yinyifu/cse442_watch
refs/heads/master
applewatch_mapping/ViewController.swift
mit
1
// // ViewController.swift // applewatch_mapping // // Created by yifu on 9/6/17. // Copyright © 2017 CSE442_UB. All rights reserved. // import UIKit import MapKit import CoreLocation import GoogleMaps import GooglePlaces //@interface MyLocationViewController : UIViewController <CLLocationManagerDelegate> class ViewController: UIViewController { let _sc : SessionController = SessionController(); private var mapController : MapController?; @IBAction func autocompleteClicked(_ sender: UIButton) { let autocompleteController = GMSAutocompleteViewController() autocompleteController.delegate = self present(autocompleteController, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad(); } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? MapController, segue.identifier == "goMapSegue" { self.mapController = vc }else{ NSLog("Motherfucker didnt prepare"); } } func alerting(title: String, message: String){ let alert = UIAlertController(title: title, message: message, preferredStyle : UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } //trying to make uiimage @objc func getLoc(sender: UIButton, event: UIEvent){ // _sc.send_image() } } extension ViewController : GMSAutocompleteViewControllerDelegate { // Handle the user's selection. func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { // runner.setCenter(place.coordinate) //let sboar : UIStoryboard = UIStoryboard(name:"Main", bundle:nil); if let map = self.mapController{ map.routeTo(place.coordinate); }else{ NSLog("Motherfucker didnt coord"); } NSLog("coor is \(place.coordinate.latitude) + \(place.coordinate.longitude)"); NSLog("runner is nil"); dismiss(animated: true, completion: nil) } func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) { // TODO: handle the error. print("Error: ", error.localizedDescription) } // User canceled the operation. func wasCancelled(_ viewController: GMSAutocompleteViewController) { dismiss(animated: true, completion: nil) } // Turn the network activity indicator on and off again. func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } } // let camera = GMSCamera //let singleTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.switchView)) //singleTap.numberOfTapsRequired = 1 // you can change this value //image.isUserInteractionEnabled = true; //image.addGestureRecognizer(singleTap); /*mapview.delegate = mapCon; let mkc : MKCoordinateRegion = MKCoordinateRegionMake(CLLocationCoordinate2D(latitude: 30, longitude: 80), MKCoordinateSpan(latitudeDelta: 0.3, longitudeDelta: 0.2)); mapview.setRegion(mkc, animated: true) // Do any additional setup after loading the view, typically from a nib. //sc.send_image(); mapCon.map_prepare(mapview: mapview) do{ try mapCon.startGettingLocations() }catch(LocationException.authorizationDenied){ alerting(title : "Authorization Denied", message : "Map service needs your location info."); locationMan.requestAlwaysAuthorization(); }catch(LocationException.authorizationRestricted){ NSLog("error: authorization restricted") }catch(LocationException.authorizationUndetermined){ NSLog("error: authorization udetermined") }catch(LocationException.locationServiceNotEnabled){ NSLog("error: location not enable") }catch(LocationException.locDelNotSet){ NSLog("error: no deleagte for locations") }catch(LocationException.mapViewNotSet){ NSLog("error: no map view") }catch{ NSLog("error: some error idk") }*/ /*} @IBAction func getLocation(sender: UIButton, event: UIEvent){ do { let userLoc: CLLocation? = try self.mapCon.getUserCurrentLocation(); if let coor:CLLocationCoordinate2D = userLoc?.coordinate{ mapview.setCenter(coor, animated: true); } }catch(LocationException.authorizationDenied){ print("Some means to error handling") } catch(LocationException.authorizationRestricted){} catch(LocationException.authorizationUndetermined){} catch{} } @objc func get_c(sender: UIButton, event: UIEvent){ do { let userLoc: CLLocation? = try self.mapCon.getUserCurrentLocation(); if(userLoc == nil){ longLabel.text = String("nil") alerting(title : "nil", message : "why are you nil?"); } if userLoc != nil{ let coor : CLLocationCoordinate2D = userLoc!.coordinate; let lat :CLLocationDegrees = coor.latitude let long :CLLocationDegrees = coor.longitude longLabel.text = String(lat) latLabel.text = String(long) //mapview.setCenter(coor, animated: true) } }catch(LocationException.authorizationDenied){ longLabel.text = String("denied") } catch(LocationException.authorizationRestricted){ longLabel.text = String("restri") } catch(LocationException.authorizationUndetermined){ longLabel.text = String("undeter") } catch{ longLabel.text = String("other") } } */ /* override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } */
4c66bd0a248f0c31b8272672b1f1abbc
30.478495
167
0.719214
false
false
false
false
chernyog/CYWeibo
refs/heads/master
CYWeibo/CYWeibo/CYWeibo/Classes/UI/Main/MainTabBar.swift
mit
1
// // MainTabBar.swift // CYWeibo // // Created by 陈勇 on 15/3/5. // Copyright (c) 2015年 zhssit. All rights reserved. // import UIKit class MainTabBar: UITabBar { // MARK: - 成员变量 /// “撰写微博”按钮点击回调 var composeButtonClicked:(() -> ())? // MARK: - 系统方法 override func drawRect(rect: CGRect) { // 绘制背景色 let image = UIImage(named:"tabbar_background")! image.drawInRect(rect) } override func awakeFromNib() { // 添加“+”按钮 addComposeButton() } override func layoutSubviews() { super.layoutSubviews() // printLine() var index = 0 let width = UIScreen.mainScreen().bounds.size.width let height = self.frame.size.height let subViewCount = 5 let w = width / CGFloat(subViewCount) let h = height // println(self.frame) for view in self.subviews as! [UIView] { if view is UIControl { // println(view) if !(view is UIButton) { view.frame = CGRect(x: CGFloat(index) * w, y: 0, width: w, height: h) index++ // 把中间那个位置空着 if index == 2 { index++ } } else // 调整“撰写微博”按钮的位置 { view.frame = CGRect(x: 0, y: 0, width: w, height: h) view.center = CGPoint(x: self.center.x, y: h * 0.5) } } } } // MARK: - 私有方法 /// 添加撰写微博按钮 func addComposeButton() { let composeBtn = UIButton() // 设置按钮的背景和前景图片 composeBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal) composeBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted) composeBtn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal) composeBtn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted) composeBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30) // 监听按钮点击事件 composeBtn.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(composeBtn) } func composeButtonClick() { // 弹出试图控制器 // 通知 代理 闭包 if self.composeButtonClicked != nil { // 回调 弹出控制器的操作应该由控制器完成! composeButtonClicked!() } } }
f67f070a6d435be5821063b263757e57
26.903226
114
0.524085
false
false
false
false
seaburg/FormattedTextField
refs/heads/master
FormattedTextField/FormattedTextField.swift
mit
1
// // FormattedTextField.swift // FormattedTextField // // Created by Evgeniy Yurtaev on 16/10/2016. // // import UIKit @objc public protocol FormattedTextFieldDelegate: UITextFieldDelegate { @objc optional func textField(_ textField: UITextField, shouldChangeUnformattedText text: String, in range: NSRange, replacementString: String) -> Bool } open class FormattedTextField: UITextField { public typealias Delegate = FormattedTextFieldDelegate public enum PlaceholderMode { case whileEmpty case always } deinit { removeTarget(self, action: #selector(self.textViewEditingChanged(_:)), for: .editingChanged) } public override init(frame: CGRect) { super.init(frame: frame) commonInitFormattedTextField() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInitFormattedTextField() } private func commonInitFormattedTextField() { delegateProxy.shouldChangeHandler = { [unowned self] (range, string) in return self.shouldChangeCharacters(in: range, replacementString: string) } delegateProxy.shouldClearHandler = { [unowned self] in return self.shouldClear() } delegateProxy.delegate = super.delegate super.delegate = delegateProxy if let unformattedText = unformattedText { if let formatter = textFormatter { text = formatter.formattedText(from: unformattedText) } else { text = unformattedText } } placeholderLabel.font = font placeholderLabel.textColor = UIColor(white: 170/255.0, alpha: 0.5) if let attributedPlaceholder = super.attributedPlaceholder { placeholderLabel.attributedText = attributedPlaceholder } else if let placeholder = super.placeholder { placeholderLabel.text = placeholder } addSubview(placeholderLabel) addTarget(self, action: #selector(self.textViewEditingChanged(_:)), for: .editingChanged) if #available(iOS 11, *) { if smartInsertDeleteType != .no { print("[FormattedTextField] warning: smartInsertDeleteType is unsupported"); } } } open var textFormatter: TextFromatter? { didSet(oldFormatter) { let text = (self.text ?? "") let selectedRange = selectedCharactersRange ?? text.startIndex..<text.startIndex var unformattedText = text var unformattedRange = selectedRange if let oldFormatter = oldFormatter { (unformattedText, unformattedRange) = oldFormatter.unformattedText(from: text, range: selectedRange) } var formattedText = unformattedText var formattedRange = unformattedRange if let formatter = textFormatter { (formattedText, formattedRange) = formatter.formattedText(from: unformattedText, range: unformattedRange) } self.text = formattedText if selectedTextRange != nil { selectedCharactersRange = formattedRange.upperBound..<formattedRange.upperBound } } } @IBInspectable open var unformattedText: String? { get { guard let text = text else { return nil } guard let formatter = textFormatter else { return text } let unformattedText = formatter.unformattedText(from: text) return unformattedText } set(value) { var formattedText = (value ?? "") if let formatter = textFormatter { formattedText = formatter.formattedText(from: formattedText) } if !formattedText.isEmpty || value != nil { text = formattedText } else { text = nil } } } open override var attributedText: NSAttributedString? { get { return super.attributedText } set(value) { assertionFailure("masked text field unsupports attributed text") } } open var placeholderMode: PlaceholderMode = .whileEmpty { didSet { setNeedsLayout() } } open override var placeholder: String? { get { return placeholderLabel.text } set(value) { placeholderLabel.text = value setNeedsLayout() } } open override var attributedPlaceholder: NSAttributedString? { get { return placeholderLabel.attributedText } set(value) { placeholderLabel.attributedText = value } } open override var font: UIFont? { get { return super.font } set(value) { super.font = value placeholderLabel.font = super.font } } open override var textAlignment: NSTextAlignment { get { return super.textAlignment } set { super.textAlignment = newValue setNeedsLayout() } } open override var delegate: UITextFieldDelegate? { get { return delegateProxy } set(value) { delegateProxy.delegate = value } } open override func layoutSubviews() { super.layoutSubviews() layoutPlaceholder() } open override func editingRect(forBounds bounds: CGRect) -> CGRect { return super.editingRect(forBounds: bounds).inset(by: textRectInset) } open override func textRect(forBounds bounds: CGRect) -> CGRect { return super.textRect(forBounds: bounds).inset(by: textRectInset) } // MARK: - Private private var textRectInset: UIEdgeInsets { return isPlaceholderVisible ? UIEdgeInsets(top: 0, left: 0, bottom: 0, right: placeholderLabelWidth) : .zero } @objc private func textViewEditingChanged(_ sender: AnyObject?) { layoutPlaceholder() } private func layoutPlaceholder() { placeholderLabel.frame = placeholderFrame } private var placeholderFrame: CGRect { if !isPlaceholderVisible { return .zero } let textRect = isEditing ? editingRect(forBounds: bounds) : self.textRect(forBounds: bounds) var placeholderLabelFrame = textRect placeholderLabelFrame.size.width = placeholderLabelWidth switch textAlignment { case .center: placeholderLabelFrame.origin.x = textRect.midX + enteredTextWidth * 0.5 case .left, .justified: fallthrough case .natural where UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .leftToRight: placeholderLabelFrame.origin.x += enteredTextWidth case .right: placeholderLabelFrame.origin.x = textRect.maxX default: // TODO: Add support for right-to-left direction placeholderLabelFrame = .zero } return placeholderLabelFrame } private var isPlaceholderVisible: Bool { if placeholder?.isEmpty ?? true { return false } // Hides placeholder before text field adds scrolling text var isVisible = (placeholderAndTextRect.width - enteredTextWidth - placeholderHiddingGap >= placeholderLabelWidth) if isVisible { switch placeholderMode { case .always: isVisible = true case .whileEmpty: isVisible = unformattedText?.isEmpty ?? true } } return isVisible } private var placeholderAndTextRect: CGRect { return isEditing ? super.editingRect(forBounds: bounds) : super.textRect(forBounds: bounds) } // UITextFields adds scrolling before entered text fills all available width private var placeholderHiddingGap: CGFloat = 10 private var enteredTextWidth: CGFloat { guard let text = self.text else { return 0 } var attributes: [NSAttributedString.Key: Any]? = nil if let placeholderFont = font { attributes = [ .font: placeholderFont] } return (text as NSString).size(withAttributes: attributes).width } private var placeholderLabelWidth: CGFloat { return placeholderLabel.sizeThatFits(CGSize(width: CGFloat.infinity, height: CGFloat.infinity)).width } private let placeholderLabel: UILabel = UILabel() private let delegateProxy: TextFieldDelegateProxy = TextFieldDelegateProxy() private func shouldChangeCharacters(in range: NSRange, replacementString string: String) -> Bool { if let shouldChange = delegateProxy.delegate?.textField?(self, shouldChangeCharactersIn: range, replacementString: string) { if !shouldChange { return false } } let text = self.text ?? "" guard let charactersRange = text.range(fromUtf16NsRange: range) else { return false } let unformattedText: String var unformattedRange: Range<String.Index> if let formatter = textFormatter { (unformattedText, unformattedRange) = formatter.unformattedText(from: text, range: charactersRange) } else { unformattedText = text unformattedRange = charactersRange } let isBackspace = (string.isEmpty && unformattedRange.isEmpty) if isBackspace && unformattedRange.lowerBound != unformattedText.startIndex { unformattedRange = unformattedText.index(before: unformattedRange.lowerBound)..<unformattedRange.upperBound } if let originDelegate = (delegateProxy.delegate as? Delegate), originDelegate.responds(to: #selector(FormattedTextFieldDelegate.textField(_:shouldChangeUnformattedText:in:replacementString:))) { guard let utf16UnformattedRange = unformattedText.utf16Nsrange(fromRange: unformattedRange) else { return false } if !originDelegate.textField!(self, shouldChangeUnformattedText:unformattedText, in:utf16UnformattedRange, replacementString: string) { return false } } let newUnformattedText = unformattedText.replacingCharacters(in: unformattedRange, with: string) let selectionOffset = unformattedText.distance(from: unformattedText.startIndex, to: unformattedRange.lowerBound) let cursorPosition = newUnformattedText.index(newUnformattedText.startIndex, offsetBy: selectionOffset + string.count) let formattedText: String let formattedRange: Range<String.Index> if let formatter = textFormatter { (formattedText, formattedRange) = formatter.formattedText(from: newUnformattedText, range: cursorPosition..<cursorPosition) } else { formattedText = newUnformattedText formattedRange = cursorPosition..<cursorPosition } self.text = formattedText selectedCharactersRange = formattedRange.upperBound..<formattedRange.upperBound sendActions(for: .editingChanged) return false } private func shouldClear() -> Bool { if let shouldClear = delegateProxy.delegate?.textFieldShouldClear?(self), !shouldClear { return false } unformattedText = nil sendActions(for: .editingChanged) return false } } // MARK: - TextFieldDelegateProxy private class TextFieldDelegateProxy: NSObject, UITextFieldDelegate { weak var delegate: UITextFieldDelegate? var shouldChangeHandler: ((NSRange, String) -> Bool)? var shouldClearHandler: (() -> Bool)? func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return delegate?.textFieldShouldBeginEditing?(textField) ?? true } func textFieldDidBeginEditing(_ textField: UITextField) { delegate?.textFieldDidBeginEditing?(textField) } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return delegate?.textFieldShouldEndEditing?(textField) ?? true } func textFieldDidEndEditing(_ textField: UITextField) { delegate?.textFieldDidEndEditing?(textField) } @available(iOS 10.0, *) func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { delegate?.textFieldDidEndEditing?(textField, reason: reason) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return shouldChangeHandler?(range, string) ?? true } func textFieldShouldClear(_ textField: UITextField) -> Bool { return shouldClearHandler?() ?? true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return delegate?.textFieldShouldReturn?(textField) ?? true } }
a8b98b74ee3cc7e06d72fbceed361c87
32.70437
155
0.637022
false
false
false
false
coderZsq/coderZsq.target.swift
refs/heads/master
StudyNotes/Swift Note/CS193p/iOS11/EmojiArtForDocument/EmojiArtViewController.swift
mit
1
// // EmojiArtViewController.swift // EmojiArt // // Created by 朱双泉 on 2018/5/15. // Copyright © 2018 Castie!. All rights reserved. // import UIKit import MobileCoreServices extension EmojiArt.EmojiInfo { init?(label: UILabel) { if let attributedText = label.attributedText, let font = attributedText.font { x = Int(label.center.x) y = Int(label.center.y) text = attributedText.string size = Int(font.pointSize) } else { return nil } } } class EmojiArtViewController: UIViewController, UIDropInteractionDelegate, UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDragDelegate, UICollectionViewDropDelegate, UIPopoverPresentationControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var cameraButton: UIBarButtonItem! { didSet { cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) } } @IBAction func takeBackgroundPhoto(_ sender: UIBarButtonItem) { let picker = UIImagePickerController() picker.sourceType = .camera picker.mediaTypes = [kUTTypeImage as String] picker.allowsEditing = true picker.delegate = self present(picker, animated: true) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.presentingViewController?.dismiss(animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = ((info[UIImagePickerControllerEditedImage] ?? info[UIImagePickerControllerOriginalImage]) as? UIImage)?.scaled(by: 0.25) { // let url = image.storeLocallyAsJPEG(named: String(Date.timeIntervalSinceReferenceDate)) if let imageData = UIImageJPEGRepresentation(image, 1.0) { emojiArtBackgroundImage = .local(imageData, image) } else { //TODO: alert user of bad camera input } documentChanged() } picker.presentingViewController?.dismiss(animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Show Document Info" { if let destination = segue.destination.contents as? DocumentInfoViewController { document?.thumbnail = emojiArtView.snapshot destination.document = document if let ppc = destination.popoverPresentationController { ppc.delegate = self } } } else if segue.identifier == "Embed Document Info" { embededDocInfo = segue.destination.contents as? DocumentInfoViewController } } private var embededDocInfo: DocumentInfoViewController? func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } @IBAction func close(bySegue: UIStoryboardSegue) { close() } @IBOutlet weak var embeddedDocInfoWidth: NSLayoutConstraint! @IBOutlet weak var embeddedDocInfoHeight: NSLayoutConstraint! var emojiArt: EmojiArt? { get { if let imageSource = emojiArtBackgroundImage { let emojis = emojiArtView.subviews.compactMap { $0 as? UILabel }.compactMap { EmojiArt.EmojiInfo(label: $0) } switch imageSource { case .remote(let url, _): return EmojiArt(url: url, emojis: emojis) case .local(let imageData, _): return EmojiArt(imageData: imageData, emojis: emojis) } } return nil } set { emojiArtBackgroundImage = nil emojiArtView.subviews.compactMap { $0 as? UILabel }.forEach { $0.removeFromSuperview() } let imageData = newValue?.imageData let image = (imageData != nil) ? UIImage(data: imageData!) : nil if let url = newValue?.url { imageFetcher = ImageFetcher(fetch: url) { (url, image) in DispatchQueue.main.async { if image == self.imageFetcher.backup { self.emojiArtBackgroundImage = .local(imageData!, image) } else { self.emojiArtBackgroundImage = .remote(url, image) } newValue?.emojis.forEach { let attributedText = $0.text.attributedString(withTextStyle: .body, ofSize: CGFloat($0.size)) self.emojiArtView.addLabel(with: attributedText, centeredAt: CGPoint(x: $0.x, y: $0.y)) } } } imageFetcher.backup = image imageFetcher.fetch(url) } else if image != nil { emojiArtBackgroundImage = .local(imageData!, image!) newValue?.emojis.forEach { let attributedText = $0.text.attributedString(withTextStyle: .body, ofSize: CGFloat($0.size)) self.emojiArtView.addLabel(with: attributedText, centeredAt: CGPoint(x: $0.x, y: $0.y)) } } } } var document: EmojiArtDocument? // @IBAction func save(_ sender: UIBarButtonItem? = nil) { func documentChanged() { document?.emojiArt = emojiArt if document?.emojiArt != nil { document?.updateChangeCount(.done) } } @IBAction func close(_ sender: UIBarButtonItem? = nil) { // save() if let observer = emojiArtViewObserver { NotificationCenter.default.removeObserver(observer) } if document?.emojiArt != nil { document?.thumbnail = emojiArtView.snapshot } presentingViewController?.dismiss(animated: true) { self.document?.close { success in if let observer = self.documentObserver { NotificationCenter.default.removeObserver(observer) } } } } private var documentObserver: NSObjectProtocol? private var emojiArtViewObserver: NSObjectProtocol? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if document?.documentState != .normal { documentObserver = NotificationCenter.default.addObserver( forName: Notification.Name.UIDocumentStateChanged, object: document, queue: OperationQueue.main, using: { notification in print("documentState changed to \(self.document!.documentState)") if self.document!.documentState == .normal, let docInfoVC = self.embededDocInfo { docInfoVC.document = self.document self.embeddedDocInfoWidth.constant = docInfoVC.preferredContentSize.width self.embeddedDocInfoHeight.constant = docInfoVC.preferredContentSize.height } } ) document?.open { success in if success { self.title = self.document?.localizedName self.emojiArt = self.document?.emojiArt self.emojiArtViewObserver = NotificationCenter.default.addObserver( forName: .EmojiArtViewDidChange, object: self.emojiArtView, queue: OperationQueue.main, using: { notification in self.documentChanged() }) } } } } // override func viewDidLoad() { // super.viewDidLoad() // if let url = try? FileManager.default.url( // for: .documentDirectory, // in: .userDomainMask, // appropriateFor: nil, // create: true // ).appendingPathComponent("Untitled.json") { // document = EmojiArtDocument(fileURL: url) // } // } @IBOutlet weak var dropZone: UIView! { didSet { dropZone.addInteraction(UIDropInteraction(delegate: self)) } } var emojiArtView = EmojiArtView() @IBOutlet weak var scrollViewHeight: NSLayoutConstraint! @IBOutlet weak var scrollViewWidth: NSLayoutConstraint! @IBOutlet weak var scrollView: UIScrollView! { didSet { scrollView.minimumZoomScale = 0.1 scrollView.maximumZoomScale = 5.0 scrollView.delegate = self scrollView.addSubview(emojiArtView) } } func scrollViewDidZoom(_ scrollView: UIScrollView) { scrollViewHeight.constant = scrollView.contentSize.height scrollViewWidth.constant = scrollView.contentSize.width } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return emojiArtView } private var _emojiArtBackgroundImageURL: URL? enum ImageSource { case remote(URL, UIImage) case local(Data, UIImage) var image: UIImage { switch self { case .remote(_, let image): return image case .local(_, let image): return image } } } var emojiArtBackgroundImage: ImageSource? { didSet { scrollView?.zoomScale = 1.0 emojiArtView.backgroundImage = emojiArtBackgroundImage?.image let size = emojiArtBackgroundImage?.image.size ?? CGSize.zero emojiArtView.frame = CGRect(origin: CGPoint.zero, size: size) scrollView?.contentSize = size scrollViewHeight?.constant = size.height scrollViewWidth?.constant = size.width if let dropZone = self.dropZone, size.width > 0, size.height > 0 { scrollView?.zoomScale = max(dropZone.bounds.size.width / size.width, dropZone.bounds.size.height / size.height) } } } @IBOutlet weak var emojiCollectionView: UICollectionView! { didSet { emojiCollectionView.dataSource = self emojiCollectionView.delegate = self emojiCollectionView.dragDelegate = self emojiCollectionView.dropDelegate = self emojiCollectionView.dragInteractionEnabled = true } } var emojis = "😀🎁✈️🎱🍎🐶🐝☕️🎼🚲♣️👨‍🎓✏️🌈🤡🎓👻☎️".map { String($0) } private var font: UIFont { return UIFontMetrics(forTextStyle: .body).scaledFont(for: UIFont.preferredFont(forTextStyle: .body).withSize(64.0)) } private var addingEmoji = false @IBAction func addEmoji() { addingEmoji = true emojiCollectionView.reloadSections(IndexSet(integer: 0)) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return emojis.count default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EmojiCell", for: indexPath) if let emojiCell = cell as? EmojiCollectionViewCell { let text = NSAttributedString(string: emojis[indexPath.row], attributes: [.font : font]) emojiCell.label.attributedText = text } return cell } else if addingEmoji { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EmojiInputCell", for: indexPath) if let inputCell = cell as? TextFieldCollectionViewCell { inputCell.resignationHandler = { [weak self, unowned inputCell] in if let text = inputCell.textField.text { self?.emojis = (text.map { String($0) } + self!.emojis).uniquified } self?.addingEmoji = false self?.emojiCollectionView.reloadData() } } return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddEmojiButtonCell", for: indexPath) return cell } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if addingEmoji && indexPath.section == 0 { return CGSize(width: 300, height: 80) } else { return CGSize(width: 80, height: 80) } } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let inputCell = cell as? TextFieldCollectionViewCell { inputCell.textField.becomeFirstResponder() } } func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { session.localContext = collectionView return dragItems(at: indexPath) } func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] { return dragItems(at: indexPath) } private func dragItems(at indexPath: IndexPath) -> [UIDragItem] { if !addingEmoji ,let attributedString = (emojiCollectionView.cellForItem(at: indexPath) as? EmojiCollectionViewCell)?.label.attributedText { let dragItem = UIDragItem(itemProvider: NSItemProvider(object: attributedString)) dragItem.localObject = attributedString return [dragItem] } else { return [] } } func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool { return session.canLoadObjects(ofClass: NSAttributedString.self) } func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal { if let indexPath = destinationIndexPath, indexPath.section == 1 { let isSelf = (session.localDragSession?.localContext as? UICollectionView) == collectionView return UICollectionViewDropProposal(operation: isSelf ? .move : .copy, intent: .insertAtDestinationIndexPath) } else { return UICollectionViewDropProposal(operation: .cancel) } } func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) { let destinationIndexPath = coordinator.destinationIndexPath ?? IndexPath(item: 0, section: 0) for item in coordinator.items { if let sourseIndexPath = item.sourceIndexPath { if let attributedString = item.dragItem.localObject as? NSAttributedString { collectionView.performBatchUpdates({ emojis.remove(at: sourseIndexPath.item) emojis.insert(attributedString.string, at: destinationIndexPath.item) collectionView.deleteItems(at: [sourseIndexPath]) collectionView.insertItems(at: [destinationIndexPath]) }) coordinator.drop(item.dragItem, toItemAt: destinationIndexPath) } } else { let placeholderContext = coordinator.drop(item.dragItem, to: UICollectionViewDropPlaceholder(insertionIndexPath: destinationIndexPath, reuseIdentifier: "DropPlaceholderCell")) item.dragItem.itemProvider.loadObject(ofClass: NSAttributedString.self) { (provider, error) in DispatchQueue.main.async { if let attributedString = provider as? NSAttributedString { placeholderContext.commitInsertion(dataSourceUpdates: { insertionIndexPath in self.emojis.insert(attributedString.string, at: insertionIndexPath.item) }) } else { placeholderContext.deletePlaceholder() } } } } } } func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { return session.canLoadObjects(ofClass: NSURL.self) && session.canLoadObjects(ofClass: UIImage.self) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { return UIDropProposal(operation: .copy) } var imageFetcher: ImageFetcher! private var suppressBadURLWarnings = false private func presentBadURLWarning(for url: URL?) { if !suppressBadURLWarnings { let alert = UIAlertController( title: "Image Transfer Failed", message: "Couldn't transfer the dropped image from its source\nShow this warning in the future?", preferredStyle: .alert ) alert.addAction(UIAlertAction( title: "Keep Warning", style: .default )) alert.addAction(UIAlertAction( title: "Stop Warning", style: .destructive, handler: { action in self.suppressBadURLWarnings = true } )) present(alert, animated: true) } } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { imageFetcher = ImageFetcher() { (url, image) in DispatchQueue.main.async { if image == self.imageFetcher.backup { if let imageData = UIImageJPEGRepresentation(image, 1.0) { self.emojiArtBackgroundImage = .local(imageData, image) self.documentChanged() } else { self.presentBadURLWarning(for: url) } } else { self.emojiArtBackgroundImage = .remote(url, image) self.documentChanged() } } } session.loadObjects(ofClass: NSURL.self) { nsurls in if let url = nsurls.first as? URL { self.imageFetcher.fetch(url) // DispatchQueue.global(qos: .userInitiated).async { // if let imageData = try? Data(contentsOf: url.imageURL), let image = UIImage(data: imageData) { // DispatchQueue.main.async { // self.emojiArtBackgroundImage = (url, image) // self.documentChanged() // } // } else { // self.presentBadURLWarning(for: url) // } // } } } session.loadObjects(ofClass: UIImage.self) { images in if let image = images.first as? UIImage { self.imageFetcher.backup = image } } } }
e06455e4d8832cac5632bbfa70b7d8df
40.886316
353
0.59223
false
false
false
false
jisudong555/swift
refs/heads/master
weibo/weibo/Classes/Models/UserAccount.swift
mit
1
// // UserAccount.swift // weibo // // Created by jisudong on 16/4/25. // Copyright © 2016年 jisudong. All rights reserved. // import UIKit // Swift2.0 打印对象需要重写CustomStringConvertible协议中的description class UserAccount: NSObject, NSCoding { /// 用于调用access_token,接口获取授权后的access token var access_token: String? /// access_token的生命周期,单位是秒数 var expires_in: NSNumber? { didSet { expire_Date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue) print(expire_Date) } } /// 当前授权用户的UID var uid: String? /// 保存用户的过期时间 var expire_Date: NSDate? /// 用户昵称 var screen_name: String? /// 用户头像地址 var avatar_large: String? init(dict: [String: AnyObject]) { super.init() // access_token = dict["access_token"] as? String // // expires_in = dict["expires_in"] as? NSNumber // uid = dict["uid"] as? String setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { print(key) } /// 重写description override var description: String { let properties = ["access_token", "expires_in", "uid", "expire_Date", "screen_name", "avatar_large"] let dict = self.dictionaryWithValuesForKeys(properties) return "\(dict)" } func loadUserInfo(finished: (account: UserAccount?, error: NSError?) -> ()) { assert(access_token != nil, "没有授权") let path = "https://api.weibo.com/2/users/show.json" let params = ["access_token": access_token!, "uid": uid!] Alamofire.request(.GET, path, parameters: params, encoding: ParameterEncoding.URL, headers: nil) .responseJSON { (response) in if let dict = response.result.value as? [String: AnyObject] { self.screen_name = dict["screen_name"] as? String self.avatar_large = dict["avatar_large"] as? String finished(account: self, error: nil) return } finished(account: nil, error: response.result.error) } } class func userLogin() -> Bool { return UserAccount.loadAccount() != nil } /** 保存授权模型 */ func saveAccount() { NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cacheDir()) } /// 加载授权模型 static var account: UserAccount? class func loadAccount() -> UserAccount? { if account != nil { return account } account = NSKeyedUnarchiver.unarchiveObjectWithFile("account.plist".cacheDir()) as? UserAccount // 判断授权是否过期 if account?.expire_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending { // 已经过期 return nil } return account } // MARK: - NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeObject(expires_in, forKey: "expires_in") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(expire_Date, forKey: "expire_Date") aCoder.encodeObject(screen_name, forKey: "screen_name") aCoder.encodeObject(avatar_large, forKey: "avatar_large") } required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber uid = aDecoder.decodeObjectForKey("uid") as? String expire_Date = aDecoder.decodeObjectForKey("expire_Date") as? NSDate screen_name = aDecoder.decodeObjectForKey("screen_name") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String } }
39f17f01a1dc90ee53eeca4b7bf7fdd1
29.389313
108
0.584024
false
false
false
false
bradhilton/SortedSet
refs/heads/master
Sources/SortedSet.swift
mit
1
// // SortedSet.swift // SortedSet // // Created by Bradley Hilton on 2/19/16. // Copyright © 2016 Brad Hilton. All rights reserved. // /// An ordered collection of unique `Element` instances public struct SortedSet<Element : Hashable & Comparable> : Hashable, RandomAccessCollection { public typealias Indices = DefaultIndices<SortedSet<Element>> var array: [Element] var set: Set<Element> /// Always zero, which is the index of the first element when non-empty. public var startIndex: Int { return array.startIndex } /// A "past-the-end" element index; the successor of the last valid /// subscript argument. public var endIndex: Int { return array.endIndex } public func index(after i: Int) -> Int { return array.index(after: i) } public func index(before i: Int) -> Int { return array.index(before: i) } public subscript(position: Int) -> Element { return array[position] } public func hash(into hasher: inout Hasher) { hasher.combine(set) } public func indexOf(_ element: Element) -> Int? { guard set.contains(element) else { return nil } return indexOf(element, in: range) } var range: Range<Int> { return Range(uncheckedBounds: (startIndex, endIndex)) } func indexOf(_ element: Element, in range: Range<Int>) -> Int { guard range.count > 2 else { return element == array[range.lowerBound] ? range.lowerBound : (range.upperBound - 1) } let middleIndex = (range.lowerBound + range.upperBound)/2 let middle = self[middleIndex] if element < middle { return indexOf(element, in: range.lowerBound..<middleIndex) } else { return indexOf(element, in: middleIndex..<range.upperBound) } } /// Construct from an arbitrary sequence with elements of type `Element`. public init<S : Sequence>(_ s: S, presorted: Bool = false, noDuplicates: Bool = false) where S.Iterator.Element == Element { if noDuplicates { if presorted { (self.array, self.set) = (Array(s), Set(s)) } else { (self.array, self.set) = (s.sorted(), Set(s)) } } else { if presorted { (self.array, self.set) = collapse(s) } else { (self.array, self.set) = collapse(s.sorted()) } } } /// Construct an empty SortedSet. public init() { self.array = [] self.set = [] } } public func ==<T>(lhs: SortedSet<T>, rhs: SortedSet<T>) -> Bool { guard lhs.count == rhs.count else { return false } for (lhs, rhs) in zip(lhs, rhs) where lhs != rhs { return false } return true } extension Array where Element : Comparable & Hashable { /// Cast SortedSet as an Array public init(_ sortedSet: SortedSet<Element>) { self = sortedSet.array } } extension Set where Element : Comparable { /// Cast SortedSet as a Set public init(_ sortedSet: SortedSet<Element>) { self = sortedSet.set } }
c0875a60a1a979851f171eacbf001a35
26.158333
128
0.574409
false
false
false
false
erikmartens/NearbyWeather
refs/heads/develop
NearbyWeather/Commons/Factory/Factory+CAGradientLayer.swift
mit
1
// // Factory+CAGradientLayer.swift // NearbyWeather // // Created by Erik Maximilian Martens on 19.03.22. // Copyright © 2022 Erik Maximilian Martens. All rights reserved. // import QuartzCore.CAGradientLayer import UIKit extension Factory { struct GradientLayer: FactoryFunction { enum GradientLayerType { case weatherCell(frame: CGRect, cornerRadiusWeight: Weight, baseColor: UIColor) } typealias InputType = GradientLayerType typealias ResultType = CAGradientLayer static func make(fromType type: InputType) -> ResultType { let gardientLayer = CAGradientLayer() switch type { case let .weatherCell(frame, cornerRadiusWeight, baseColor): gardientLayer.frame = frame gardientLayer.cornerRadius = Constants.Dimensions.CornerRadius.from(weight: cornerRadiusWeight) gardientLayer.colors = [ (baseColor.lighten(by: 10) ?? baseColor).cgColor, baseColor.cgColor, (baseColor.darken(by: 25) ?? baseColor).cgColor ] } return gardientLayer } } }
c05165d81b0ba267c8ca85163c5fccc3
26.55
103
0.676044
false
false
false
false
castial/Quick-Start-iOS
refs/heads/master
Quick-Start-iOS/AppDelegate.swift
mit
1
// // AppDelegate.swift // Quick-Start-iOS // // Created by work on 2016/10/13. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit // MARK: - Class @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow (frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white let rootVC: RootViewController = RootViewController() window?.rootViewController = rootVC window?.makeKeyAndVisible() // 开始广告页面 // startAdvertisingPage() // 显示FPS // showFPS() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } // MARK: - 启动广告相关 extension AppDelegate { func startAdvertisingPage() { if AdHelper.isNeedShow() { // 显示公告页面 let adView: AdPageView = AdPageView (frame: CGRect (x: 0, y: 0, width: Constants.Rect.ScreenWidth, height: Constants.Rect.ScreenHeight)) adView.imageFilePath = AdHelper.adImagePath()! adView.show() } // 每次启动,都更新广告 AdHelper.refreshAdvertisingImage() } } // MARK: - 测试相关 extension AppDelegate { func showFPS() { let fpsLabel: HYFPSLabel = HYFPSLabel (frame: CGRect (x: Constants.Rect.ScreenWidth - HYFPSLabel.defaultSize.width - 5, y: Constants.Rect.ScreenHeight - HYFPSLabel.defaultSize.height - 10, width: HYFPSLabel.defaultSize.width, height: HYFPSLabel.defaultSize.height)) fpsLabel.showFPS() } }
a385cc3b9e556fa72795078e70e9e3b9
42
285
0.667974
false
false
false
false
vnu/vTweetz
refs/heads/master
Pods/SwiftDate/SwiftDate/NSDateComponents+SwiftDate.swift
apache-2.0
2
// // SwiftDate, an handy tool to manage date and timezones in swift // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation //MARK: - Extension of Int To Manage Operations - public extension NSDateComponents { /** Create a new date from a specific date by adding self components - parameter refDate: reference date - parameter region: optional region to define the timezone and calendar. By default is UTC Region - returns: a new NSDate instance in UTC format */ public func fromDate(refDate :NSDate!, inRegion region: Region = Region()) -> NSDate { let date = region.calendar.dateByAddingComponents(self, toDate: refDate, options: NSCalendarOptions(rawValue: 0)) return date! } /** Create a new date from a specific date by subtracting self components - parameter refDate: reference date - parameter region: optional region to define the timezone and calendar. By default is UTC Region - returns: a new NSDate instance in UTC format */ public func agoFromDate(refDate :NSDate!, inRegion region: Region = Region()) -> NSDate { for unit in DateInRegion.componentFlagSet { let value = self.valueForComponent(unit) if value != NSDateComponentUndefined { self.setValue((value * -1), forComponent: unit) } } return region.calendar.dateByAddingComponents(self, toDate: refDate, options: NSCalendarOptions(rawValue: 0))! } /** Create a new date from current date and add self components. So you can make something like: let date = 4.days.fromNow() - parameter region: optional region to define the timezone and calendar. By default is UTC Region - returns: a new NSDate instance in UTC format */ public func fromNow(inRegion region: Region = Region()) -> NSDate { return fromDate(NSDate(), inRegion: region) } /** Create a new date from current date and substract self components So you can make something like: let date = 5.hours.ago() - parameter region: optional region to define the timezone and calendar. By default is UTC Region - returns: a new NSDate instance in UTC format */ public func ago(inRegion region: Region = Region()) -> NSDate { return agoFromDate(NSDate()) } /// The same of calling fromNow() with default UTC region public var fromNow : NSDate { get { return fromDate(NSDate()) } } /// The same of calling ago() with default UTC region public var ago : NSDate { get { return agoFromDate(NSDate()) } } /// The dateInRegion for the current components public var dateInRegion: DateInRegion? { return DateInRegion(self) } } //MARK: - Combine NSDateComponents - public func | (lhs: NSDateComponents, rhs :NSDateComponents) -> NSDateComponents { let dc = NSDateComponents() for unit in DateInRegion.componentFlagSet { let lhs_value = lhs.valueForComponent(unit) let rhs_value = rhs.valueForComponent(unit) if lhs_value != NSDateComponentUndefined { dc.setValue(lhs_value, forComponent: unit) } if rhs_value != NSDateComponentUndefined { dc.setValue(rhs_value, forComponent: unit) } } return dc } /// Add date components to one another /// public func + (lhs: NSDateComponents, rhs: NSDateComponents) -> NSDateComponents { return sumDateComponents(lhs, rhs: rhs) } /// subtract date components from one another /// public func - (lhs: NSDateComponents, rhs: NSDateComponents) -> NSDateComponents { return sumDateComponents(lhs, rhs: rhs, sum: false) } /// Helper function for date component sum * subtract /// internal func sumDateComponents(lhs :NSDateComponents, rhs :NSDateComponents, sum :Bool = true) -> NSDateComponents { let newComponents = NSDateComponents() let components = DateInRegion.componentFlagSet for unit in components { let leftValue = lhs.valueForComponent(unit) let rightValue = rhs.valueForComponent(unit) guard leftValue != NSDateComponentUndefined || rightValue != NSDateComponentUndefined else { continue // both are undefined, don't touch } let checkedLeftValue = leftValue == NSDateComponentUndefined ? 0 : leftValue let checkedRightValue = rightValue == NSDateComponentUndefined ? 0 : rightValue let finalValue = checkedLeftValue + (sum ? checkedRightValue : -checkedRightValue) newComponents.setValue(finalValue, forComponent: unit) } return newComponents } // MARK: - Helpers to enable expressions e.g. date + 1.days - 20.seconds public extension NSTimeZone { /// Returns a new NSDateComponents object containing the time zone as specified by the receiver /// public var timeZone: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.timeZone = self return dateComponents } } public extension NSCalendar { /// Returns a new NSDateComponents object containing the calendar as specified by the receiver /// public var calendar: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.calendar = self return dateComponents } } public extension Int { /// Returns a new NSDateComponents object containing the number of nanoseconds as specified by the receiver /// public var nanoseconds: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.nanosecond = self return dateComponents } /// Returns a new NSDateComponents object containing the number of seconds as specified by the receiver /// public var seconds: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.second = self return dateComponents } /// Returns a new NSDateComponents object containing the number of minutes as specified by the receiver /// public var minutes: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.minute = self return dateComponents } /// Returns a new NSDateComponents object containing the number of hours as specified by the receiver /// public var hours: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.hour = self return dateComponents } /// Returns a new NSDateComponents object containing the number of days as specified by the receiver /// public var days: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.day = self return dateComponents } /// Returns a new NSDateComponents object containing the number of weeks as specified by the receiver /// public var weeks: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.weekOfYear = self return dateComponents } /// Returns a new NSDateComponents object containing the number of months as specified by the receiver /// public var months: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.month = self return dateComponents } /// Returns a new NSDateComponents object containing the number of years as specified by the receiver /// public var years: NSDateComponents { let dateComponents = NSDateComponents() dateComponents.year = self return dateComponents } }
6b207b7cc372946d9ca57f8f49e7dcc0
33.653696
121
0.678307
false
false
false
false
rolandpeelen/WatchSpringboard-Swift
refs/heads/master
SwiftSpringboard/Springboard/SpringboardView.swift
bsd-3-clause
1
// // SpringboardView.swift // SwiftSpringboard // // Created by Joachim Boggild on 11/08/15. // Copyright (c) 2015 Joachim Boggild. All rights reserved. // import Foundation import UIKit public class SpringboardView: UIScrollView, UIScrollViewDelegate { public var minimumZoomLevelToLaunchApp: CGFloat = 0.0 public var doubleTapGesture: UITapGestureRecognizer! private var _touchView: UIView! private var _contentView: UIView! private var _debugRectInContent: UIView! private var _debugRectInScroll: UIView! private let _ITEM_DIAMETER: CGFloat = 120; // controls how much transform we apply to the views (not used) var _transformFactor: CGFloat = 1.0 // a few state variables var _lastFocusedViewIndex: Int = 0 var _zoomScaleCache : CGFloat = 0 var _minTransform: CGAffineTransform! // dirty when the view changes width/height var _minimumZoomLevelIsDirty = false var _contentSizeIsDirty = false var _contentSizeUnscaled = CGSizeZero var _contentSizeExtra = CGSizeZero var _centerOnEndDrag = false var _centerOnEndDeccel = false // ----------------------------------------------------------------------------------------------- // MARK: // MARK: PROPERTIES private var _itemViews = [UIView](); public var itemViews: [UIView] { get { return _itemViews; } set (newViews) { if (newViews != _itemViews) { for view in _itemViews { if view.isDescendantOfView(self) { view.removeFromSuperview() } } _itemViews = newViews; for view in _itemViews { _contentView.addSubview(view); } LM_setContentSizeIsDirty(); } } } private var _itemDiameter: CGFloat = 0; public var itemDiameter: CGFloat { get { return _itemDiameter; } set (newValue) { if _itemDiameter != newValue { _itemDiameter = newValue; LM_setContentSizeIsDirty(); } } } private var _itemPadding: CGFloat = 0; public var itemPadding: CGFloat { get { return _itemPadding; } set (newValue) { if(_itemPadding != newValue) { _itemPadding = newValue; LM_setContentSizeIsDirty(); } } } private var _minimumItemScaling: CGFloat = 0; public var minimumItemScaling: CGFloat { get { return _minimumItemScaling; } set { if _minimumItemScaling != newValue { _minimumItemScaling = newValue; setNeedsLayout() } } } // ----------------------------------------------------------------------------------------------- // MARK: // MARK: INITIALIZATION init() { super.init(frame: CGRectMake(0, 0, 100, 100)); LM_initBase(); } override init(frame: CGRect) { super.init(frame: frame); LM_initBase(); } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); LM_initBase(); } // ----------------------------------------------------------------------------------------------- // MARK: // MARK: SpringboardView private func showAllContentAnimated(animated: Bool) { var contentRectInContentSpace = LM_fullContentRectInContentSpace(); _lastFocusedViewIndex = LM_closestIndexToPointInContent(LM_rectCenter(contentRectInContentSpace)); if animated == true { UIView.animateWithDuration(0.5, delay: 0, options: .LayoutSubviews | .AllowAnimatedContent | .BeginFromCurrentState | .CurveEaseInOut, animations: { () -> Void in self.zoomToRect(contentRectInContentSpace, animated: false); self.layoutIfNeeded(); }, completion: nil ) } else { zoomToRect(contentRectInContentSpace, animated: false); } } public func indexOfItemClosestToPoint(pointInSelf: CGPoint) -> Int { return LM_closestIndexToPointInSelf(pointInSelf) } public func centerOnIndex(index: Int, zoomScale: CGFloat, animated: Bool) { _lastFocusedViewIndex = index; let view = itemViews[Int(index)]; let centerContentSpace = view.center; if zoomScale != self.zoomScale { var rectInContentSpace = LM_rectWithCenter(centerContentSpace, size: view.bounds.size); // this takes the rect in content space zoomToRect(rectInContentSpace, animated: animated); } else { let sizeInSelfSpace = bounds.size let centerInSelfSpace = LM_pointInContentToSelf(centerContentSpace) let rectInSelfSpace = LM_rectWithCenter(centerInSelfSpace, size: sizeInSelfSpace) // this takes the rect in self space scrollRectToVisible(rectInSelfSpace, animated: animated) } } public func doIntroAnimation() { layoutIfNeeded(); let size = self.bounds.size; let minScale: CGFloat = 0.5; let centerView = itemViews[_lastFocusedViewIndex]; let centerViewCenter = centerView.center; for view in itemViews { let viewCenter = view.center; view.alpha = 0; let dx = (viewCenter.x - centerViewCenter.x); let dy = (viewCenter.y - centerViewCenter.y); let distance = (dx*dx-dy*dy); let factor: CGFloat = max(min(max(size.width, size.height)/distance, 1), 0); let scaleFactor = (factor) * 0.8 + 0.2; let translateFactor: CGFloat = -0.9; view.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(dx * translateFactor, dy * translateFactor), minScale * scaleFactor, minScale * scaleFactor); } setNeedsLayout(); UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in for view in self.itemViews { view.alpha = 1; } self.layoutSubviews(); }, completion: nil); } // ----------------------------------------------------------------------------------------------- // MARK: // MARK: INPUT func LM_didZoomGesture(sender: UITapGestureRecognizer) { let maximumZoom: CGFloat = 1; let positionInSelf = sender.locationInView(self); let targetIndex = LM_closestIndexToPointInSelf(positionInSelf); if zoomScale >= minimumZoomLevelToLaunchApp && zoomScale != minimumZoomScale { showAllContentAnimated(true); } else { UIView.animateWithDuration(0.5) { self.centerOnIndex(targetIndex, zoomScale: maximumZoom, animated: false) self.layoutIfNeeded(); }; } } // ----------------------------------------------------------------------------------------------- // MARK: // MARK: Privates private func LM_initBase() { println("initbase") self.delaysContentTouches = false; self.showsHorizontalScrollIndicator = false; self.showsVerticalScrollIndicator = false; self.alwaysBounceHorizontal = true; self.alwaysBounceVertical = true; self.bouncesZoom = true; self.decelerationRate = UIScrollViewDecelerationRateFast; self.delegate = self; // self.itemDiameter = 68; self.itemDiameter = _ITEM_DIAMETER + 8; self.itemPadding = 48; self.minimumItemScaling = 0.5; _transformFactor = 1; _zoomScaleCache = self.zoomScale; minimumZoomLevelToLaunchApp = 0.4; _touchView = UIView(); // _touchView.backgroundColor = UIColor.purpleColor(); addSubview(_touchView); _contentView = UIView(); //_contentView.backgroundColor = UIColor.greenColor(); addSubview(_contentView) /*_debugRectInContent = [[UIView alloc] init]; _debugRectInContent.backgroundColor = [UIColor redColor]; _debugRectInContent.alpha = 0.4; [_contentView addSubview:_debugRectInContent]; _debugRectInScroll = [[UIView alloc] init]; _debugRectInScroll.backgroundColor = [UIColor blueColor]; _debugRectInScroll.alpha= 0.4; [self addSubview:_debugRectInScroll];*/ doubleTapGesture = UITapGestureRecognizer(target: self, action: "LM_didZoomGesture:"); doubleTapGesture.numberOfTapsRequired = 1; _contentView.addGestureRecognizer(doubleTapGesture); } private func LM_pointInSelfToContent(point: CGPoint) -> CGPoint { return CGPointMake(point.x/zoomScale, point.y/zoomScale); } private func LM_pointInContentToSelf(point: CGPoint) -> CGPoint { return CGPointMake(point.x * zoomScale, point.y * zoomScale); } private func LM_sizeInSelfToContent(size: CGSize) -> CGSize { return CGSizeMake(size.width/zoomScale, size.height/zoomScale); } private func LM_sizeInContentToSelf(size: CGSize) -> CGSize { return CGSizeMake(size.width*zoomScale, size.height*zoomScale); } private func LM_rectCenter(rect: CGRect) -> CGPoint { return CGPointMake(rect.origin.x+rect.size.width*0.5, rect.origin.y+rect.size.height*0.5); } private func LM_rectWithCenter(center: CGPoint, size: CGSize) -> CGRect { return CGRectMake(center.x-size.width*0.5, center.y-size.height*0.5, size.width, size.height); } private func LM_transformView(view: SpringboardItemView) { // TODO: refactor to make functions use converter and helper functions let size = bounds.size; let zoomScale = _zoomScaleCache; let insets = contentInset; var frame = convertRect(CGRectMake(view.center.x - itemDiameter/2, view.center.y - itemDiameter/2, itemDiameter, itemDiameter), fromView: view.superview); frame.origin.x -= contentOffset.x; frame.origin.y -= contentOffset.y; let center = CGPointMake(frame.origin.x+frame.size.width/2, frame.origin.y+frame.size.height/2); let padding = itemPadding*zoomScale*0.4; var distanceToBorder: CGFloat = size.width; var xOffset: CGFloat = 0; var yOffset: CGFloat = 0; let distanceToBeOffset = itemDiameter * zoomScale * (min(size.width, size.height)/320); let leftDistance: CGFloat = center.x - padding - insets.left; if leftDistance < distanceToBeOffset { if leftDistance < distanceToBorder { distanceToBorder = leftDistance; } xOffset = 1 - leftDistance / distanceToBeOffset; } let topDistance: CGFloat = center.y - padding - insets.top; if topDistance < distanceToBeOffset { if topDistance < distanceToBorder { distanceToBorder = topDistance; } yOffset = 1 - topDistance / distanceToBeOffset; } let rightDistance: CGFloat = size.width - padding - center.x - insets.right; if rightDistance < distanceToBeOffset { if rightDistance < distanceToBorder { distanceToBorder = rightDistance; } xOffset = -(1 - rightDistance / distanceToBeOffset); } let bottomDistance: CGFloat = size.height - padding - center.y - insets.bottom; if bottomDistance < distanceToBeOffset { if bottomDistance < distanceToBorder { distanceToBorder = bottomDistance; } yOffset = -(1 - bottomDistance / distanceToBeOffset); } distanceToBorder *= 2; var usedScale: CGFloat; if distanceToBorder < distanceToBeOffset * 2{ if distanceToBorder < CGFloat(-(Int(itemDiameter*2.5))) { view.transform = _minTransform; usedScale = minimumItemScaling * zoomScale } else { var rawScale = max(distanceToBorder / (distanceToBeOffset * 2), 0); rawScale = min(rawScale, 1); rawScale = 1-pow(1-rawScale, 2); var scale: CGFloat = rawScale * (1 - minimumItemScaling) + minimumItemScaling; xOffset = frame.size.width*0.8*(1-rawScale)*xOffset; yOffset = frame.size.width*0.5*(1-rawScale)*yOffset; var translationModifier: CGFloat = min(distanceToBorder/_itemDiameter+2.5, 1); scale = max(min(scale * _transformFactor + (1 - _transformFactor), 1), 0); translationModifier = min(translationModifier * _transformFactor, 1); view.transform = CGAffineTransformTranslate(CGAffineTransformMakeScale(scale, scale), xOffset * translationModifier, yOffset * translationModifier); usedScale = scale * zoomScale; } } else { view.transform = CGAffineTransformIdentity; usedScale = zoomScale; } if dragging || zooming { view.setScale(usedScale, animated: true); } else { view.scale = usedScale; } } private func LM_setContentSizeIsDirty() { _contentSizeIsDirty = true; LM_setMinimumZoomLevelIsDirty(); } private func LM_setMinimumZoomLevelIsDirty() { _minimumZoomLevelIsDirty = true; _contentSizeIsDirty = true; setNeedsLayout(); } private func LM_closestIndexToPointInSelf(pointInSelf: CGPoint) -> Int { let pointInContent = LM_pointInSelfToContent(pointInSelf); return LM_closestIndexToPointInContent(pointInContent); } private func LM_closestIndexToPointInContent(pointInContent: CGPoint) -> Int { var hasItem = false; var distance: CGFloat = 0; var index = _lastFocusedViewIndex; var i = 0; for potentialView in itemViews { let center = potentialView.center; let potentialDistance = LMPointDistance(x1: center.x, y1: center.y, x2: pointInContent.x, y2: pointInContent.y); if potentialDistance < distance || !hasItem { hasItem = true; distance = potentialDistance; index = i; } i++; } return index; } private func LM_centerOnClosestToScreenCenterAnimated(animated: Bool) { let sizeInSelf = self.bounds.size; let centerInSelf = CGPointMake(sizeInSelf.width*0.5, sizeInSelf.height*0.5); let closestIndex = LM_closestIndexToPointInSelf(centerInSelf); centerOnIndex(closestIndex, zoomScale:self.zoomScale, animated:animated); } private func LM_fullContentRectInContentSpace() -> CGRect { let rect = CGRectMake(_contentSizeExtra.width*0.5, _contentSizeExtra.height*0.5, _contentSizeUnscaled.width-_contentSizeExtra.width, _contentSizeUnscaled.height-_contentSizeExtra.height); //_debugRectInContent.frame = rect; return rect; } private func LM_insetRectInSelf() -> CGRect { let insets = self.contentInset; let size = self.bounds.size; return CGRectMake(insets.left, insets.top, size.width-insets.left-insets.right, size.height-insets.top-insets.bottom); } private func LM_centerViewIfSmaller() { /*CGRect frameToCenter = _contentView.frame; CGRect rect = [self LM_insetRect]; // center horizontally if (frameToCenter.size.width < rect.size.width) frameToCenter.origin.x = (rect.size.width - frameToCenter.size.width) / 2; else frameToCenter.origin.x = 0; // center vertically if (frameToCenter.size.height < rect.size.height) frameToCenter.origin.y = (rect.size.height - frameToCenter.size.height) / 2; else frameToCenter.origin.y = 0; _contentView.frame = frameToCenter;*/ } private func LMPointDistance(#x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat { let temp = LKPointDistanceSquared(x1: x1, y1: y1, x2: x2, y2: y2); let d: Double = Double(temp); let sq = sqrt(d); return CGFloat(sq); } private func LKPointDistanceSquared(#x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); } // ----------------------------------------------------------------------------------------------- // MARK: // MARK: UIScrollViewDelegate public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { // TODO: refactor to make functions use converter and helper functions let size = self.bounds.size; // targetContentOffset is in coordinates relative to self; var targContOff: CGPoint = targetContentOffset.memory; // putting proposedTargetCenter in coordinates relative to _contentView var proposedTargetCenter = CGPointMake(targContOff.x+size.width/2, targContOff.y+size.height/2); proposedTargetCenter.x /= zoomScale; proposedTargetCenter.y /= zoomScale; //_debugRectInContent.frame = CGRectMake(proposedTargetCenter.x-40, proposedTargetCenter.y-40, 80, 80); // finding out the idealTargetCenter in coordinates relative to _contentView _lastFocusedViewIndex = LM_closestIndexToPointInContent(proposedTargetCenter); let view = itemViews[_lastFocusedViewIndex]; let idealTargetCenter = view.center; //_debugRectInContent.frame = CGRectMake(idealTargetCenter.x-40, idealTargetCenter.y-40, 80, 80); // finding out the idealTargetOffset in coordinates relative to _contentView let idealTargetOffset = CGPointMake(idealTargetCenter.x-size.width/2/zoomScale, idealTargetCenter.y-size.height/2/zoomScale); //_debugRectInContent.frame = CGRectMake(idealTargetOffset.x-40, idealTargetOffset.y-40, 80, 80); // finding out the correctedTargetOffset in coordinates relative to self let correctedTargetOffset = CGPointMake(idealTargetOffset.x*zoomScale, idealTargetOffset.y*zoomScale); //_debugRectInScroll.frame = CGRectMake(correctedTargetOffset.x-40, correctedTargetOffset.y-40, 80, 80); // finding out currentCenter in coordinates relative to _contentView; var currentCenter = CGPointMake(self.contentOffset.x+size.width/2, self.contentOffset.y+size.height/2); currentCenter.x /= zoomScale; currentCenter.y /= zoomScale; //_debugRectInContent.frame = CGRectMake(currentCenter.x-40, currentCenter.y-40, 80, 80); // finding out the frame of actual icons in relation to _contentView var contentCenter = _contentView.center; contentCenter.x /= zoomScale; contentCenter.y /= zoomScale; let contentSizeNoExtras = CGSizeMake(_contentSizeUnscaled.width-_contentSizeExtra.width, _contentSizeUnscaled.height-_contentSizeExtra.height); let contentFrame = CGRectMake(contentCenter.x-contentSizeNoExtras.width*0.5, contentCenter.y-contentSizeNoExtras.height*0.5, contentSizeNoExtras.width, contentSizeNoExtras.height); //_debugRectInContent.frame = contentFrame; if !CGRectContainsPoint(contentFrame, proposedTargetCenter) { // we're going to end outside if !CGRectContainsPoint(contentFrame, currentCenter) { // we're already outside. stop roll and snap back on end drag targContOff = self.contentOffset; _centerOnEndDrag = true; return; } else { // we're still in, ending out. Wait for the animation to end, THEN snap back. let ourPriority: CGFloat = 0.8; targContOff = CGPointMake( targContOff.x*(1-ourPriority)+correctedTargetOffset.x*ourPriority, targContOff.y*(1-ourPriority)+correctedTargetOffset.y*ourPriority ); _centerOnEndDeccel = true; return; } } // we're going to end in. snap to closest icon targContOff = correctedTargetOffset; targetContentOffset.memory = targContOff; } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if _centerOnEndDrag { _centerOnEndDrag = false; centerOnIndex(_lastFocusedViewIndex, zoomScale: zoomScale, animated: true); } } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if _centerOnEndDeccel { _centerOnEndDeccel = false; centerOnIndex(_lastFocusedViewIndex, zoomScale:self.zoomScale, animated:true); } } public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return _contentView; } public func scrollViewDidZoom(scrollView: UIScrollView) { _zoomScaleCache = zoomScale; LM_centerViewIfSmaller(); } // ----------------------------------------------------------------------------------------------- // MARK: // MARK: UIView public override func layoutSubviews() { super.layoutSubviews(); let size = self.bounds.size; let insets = self.contentInset; let minSide = min(size.width, size.height) let maxSide = max(size.width, size.height) let sq = sqrt(CGFloat(itemViews.count)); var itemsPerLine = ceil(minSide / maxSide * sq); if itemsPerLine % 2 == 0 { itemsPerLine++; } let lines = Int(ceil(Double(itemViews.count)/Double(itemsPerLine))); var newMinimumZoomScale:CGFloat = 0; if _contentSizeIsDirty { let padding = itemPadding; let sizeWidth = itemsPerLine*itemDiameter+(itemsPerLine+1)*padding+(itemDiameter+padding)/2; let sizeHeight = CGFloat(lines) * itemDiameter + 2 * padding _contentSizeUnscaled = CGSizeMake(sizeWidth, sizeHeight); newMinimumZoomScale = min((size.width-insets.left-insets.right)/_contentSizeUnscaled.width, (size.height-insets.top-insets.bottom)/_contentSizeUnscaled.height); _contentSizeExtra = CGSizeMake((size.width-itemDiameter*0.5)/newMinimumZoomScale, (size.height-itemDiameter*0.5)/newMinimumZoomScale); _contentSizeUnscaled.width += _contentSizeExtra.width; _contentSizeUnscaled.height += _contentSizeExtra.height; _contentView.bounds = CGRectMake(0, 0, _contentSizeUnscaled.width, _contentSizeUnscaled.height); } if _minimumZoomLevelIsDirty { minimumZoomScale = newMinimumZoomScale; let newZoom: CGFloat = max(self.zoomScale, newMinimumZoomScale); if newZoom != _zoomScaleCache || true { self.zoomScale = newZoom; _zoomScaleCache = newZoom; _contentView.center = CGPointMake(_contentSizeUnscaled.width*0.5*newZoom, _contentSizeUnscaled.height*0.5*newZoom); self.contentSize = CGSizeMake(_contentSizeUnscaled.width*newZoom, _contentSizeUnscaled.height*newZoom); } } if _contentSizeIsDirty { var i: Int = 0; for view in itemViews { view.bounds = CGRectMake(0, 0, itemDiameter, itemDiameter); var posX: CGFloat = 0; var posY: CGFloat = 0; var line: UInt = UInt(CGFloat(i)/itemsPerLine); var indexInLine: UInt = UInt(i % Int(itemsPerLine)); if i == 0 { // place item 0 at the center of the grid line = UInt(CGFloat(itemViews.count) / itemsPerLine / 2); indexInLine = UInt(itemsPerLine/2); } else { // switch item at center of grid to position 0 if line == UInt(CGFloat(itemViews.count) / itemsPerLine / 2) && indexInLine == UInt(itemsPerLine / 2) { line = 0; indexInLine = 0; } } var lineOffset: CGFloat = 0; if line % 2 == 1 { lineOffset = (itemDiameter + itemPadding) / 2; } posX = _contentSizeExtra.width * 0.5 + itemPadding + lineOffset + CGFloat(indexInLine) * (itemDiameter + itemPadding) + itemDiameter/2; posY = _contentSizeExtra.height * 0.5 + itemPadding + CGFloat(line) * itemDiameter + itemDiameter / 2; view.center = CGPointMake(posX, posY); i++; } _contentSizeIsDirty = false; } if _minimumZoomLevelIsDirty { if _lastFocusedViewIndex <= itemViews.count { centerOnIndex(_lastFocusedViewIndex, zoomScale:_zoomScaleCache, animated:false); } _minimumZoomLevelIsDirty = false; } _zoomScaleCache = self.zoomScale; _touchView.bounds = CGRectMake(0, 0, (_contentSizeUnscaled.width-_contentSizeExtra.width)*_zoomScaleCache, (_contentSizeUnscaled.height-_contentSizeExtra.height)*_zoomScaleCache); _touchView.center = CGPointMake(_contentSizeUnscaled.width*0.5*_zoomScaleCache, _contentSizeUnscaled.height*0.5*_zoomScaleCache); LM_centerViewIfSmaller(); let scale: CGFloat = min(_minimumItemScaling*_transformFactor+(1-_transformFactor), 1); _minTransform = CGAffineTransformMakeScale(scale, scale); for view in itemViews as! [SpringboardItemView] { LM_transformView(view); } } public override var bounds: CGRect { get { return super.bounds } set { if !CGSizeEqualToSize(super.bounds.size, newValue.size) { LM_setMinimumZoomLevelIsDirty(); } super.bounds = newValue; } } public override var frame: CGRect { get { return super.frame; } set { if !CGSizeEqualToSize(newValue.size, bounds.size) { LM_setMinimumZoomLevelIsDirty(); } super.frame = newValue; } } }
9c42aeb8e5b26956bfc7c4a96335fd68
30.84626
182
0.696603
false
false
false
false
GoBike/PopupDialog
refs/heads/master
Example/PopupDialog/CosmosDistrib.swift
mit
2
// // Star rating control written in Swift for iOS. // // https://github.com/marketplacer/Cosmos // // This file was automatically generated by combining multiple Swift source files. // // ---------------------------- // // CosmosAccessibility.swift // // ---------------------------- import UIKit /** Functions for making cosmos view accessible. */ struct CosmosAccessibility { /** Makes the view accesible by settings its label and using rating as value. */ static func update(_ view: UIView, rating: Double, text: String?, settings: CosmosSettings) { view.isAccessibilityElement = true view.accessibilityTraits = settings.updateOnTouch ? UIAccessibilityTraitAdjustable :UIAccessibilityTraitNone var accessibilityLabel = CosmosLocalizedRating.ratingTranslation if let text = text , text != "" { accessibilityLabel += " \(text)" } view.accessibilityLabel = accessibilityLabel view.accessibilityValue = accessibilityValue(view, rating: rating, settings: settings) } /** Returns the rating that is used as accessibility value. The accessibility value depends on the star fill mode. For example, if rating is 4.6 and fill mode is .Half the value will be 4.5. And if the fill mode if .Full the value will be 5. */ static func accessibilityValue(_ view: UIView, rating: Double, settings: CosmosSettings) -> String { let accessibilityRating = CosmosRating.displayedRatingFromPreciseRating(rating, fillMode: settings.fillMode, totalStars: settings.totalStars) // Omit decimals if the value is an integer let isInteger = (accessibilityRating * 10).truncatingRemainder(dividingBy: 10) == 0 if isInteger { return "\(Int(accessibilityRating))" } else { // Only show a single decimal place let roundedToFirstDecimalPlace = Double( round(10 * accessibilityRating) / 10 ) return "\(roundedToFirstDecimalPlace)" } } /** Returns the amount of increment for the rating. When .Half and .Precise fill modes are used the rating is incremented by 0.5. */ static func accessibilityIncrement(_ rating: Double, settings: CosmosSettings) -> Double { var increment: Double = 0 switch settings.fillMode { case .full: increment = ceil(rating) - rating if increment == 0 { increment = 1 } case .half, .precise: increment = (ceil(rating * 2) - rating * 2) / 2 if increment == 0 { increment = 0.5 } } if rating >= Double(settings.totalStars) { increment = 0 } return increment } static func accessibilityDecrement(_ rating: Double, settings: CosmosSettings) -> Double { var increment: Double = 0 switch settings.fillMode { case .full: increment = rating - floor(rating) if increment == 0 { increment = 1 } case .half, .precise: increment = (rating * 2 - floor(rating * 2)) / 2 if increment == 0 { increment = 0.5 } } if rating <= settings.minTouchRating { increment = 0 } return increment } } // ---------------------------- // // CosmosDefaultSettings.swift // // ---------------------------- import UIKit /** Defaults setting values. */ struct CosmosDefaultSettings { init() {} static let defaultColor = UIColor(red: 1, green: 149/255, blue: 0, alpha: 1) // MARK: - Star settings // ----------------------------- /// Border color of an empty star. static let emptyBorderColor = defaultColor /// Width of the border for the empty star. static let emptyBorderWidth: Double = 1 / Double(UIScreen.main.scale) /// Border color of a filled star. static let filledBorderColor = defaultColor /// Width of the border for a filled star. static let filledBorderWidth: Double = 1 / Double(UIScreen.main.scale) /// Background color of an empty star. static let emptyColor = UIColor.clear /// Background color of a filled star. static let filledColor = defaultColor /** Defines how the star is filled when the rating value is not an integer value. It can either show full stars, half stars or stars partially filled according to the rating value. */ static let fillMode = StarFillMode.full /// Rating value that is shown in the storyboard by default. static let rating: Double = 2.718281828 /// Distance between stars. static let starMargin: Double = 5 /** Array of points for drawing the star with size of 100 by 100 pixels. Supply your points if you need to draw a different shape. */ static let starPoints: [CGPoint] = [ CGPoint(x: 49.5, y: 0.0), CGPoint(x: 60.5, y: 35.0), CGPoint(x: 99.0, y: 35.0), CGPoint(x: 67.5, y: 58.0), CGPoint(x: 78.5, y: 92.0), CGPoint(x: 49.5, y: 71.0), CGPoint(x: 20.5, y: 92.0), CGPoint(x: 31.5, y: 58.0), CGPoint(x: 0.0, y: 35.0), CGPoint(x: 38.5, y: 35.0) ] /// Size of a single star. static var starSize: Double = 20 /// The total number of stars to be shown. static let totalStars = 5 // MARK: - Text settings // ----------------------------- /// Color of the text. static let textColor = UIColor(red: 127/255, green: 127/255, blue: 127/255, alpha: 1) /// Font for the text. static let textFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote) /// Distance between the text and the stars. static let textMargin: Double = 5 /// Calculates the size of the default text font. It is used for making the text size configurable from the storyboard. static var textSize: Double { get { return Double(textFont.pointSize) } } // MARK: - Touch settings // ----------------------------- /// The lowest rating that user can set by touching the stars. static let minTouchRating: Double = 1 /// When `true` the star fill level is updated when user touches the cosmos view. When `false` the Cosmos view only shows the rating and does not act as the input control. static let updateOnTouch = true } // ---------------------------- // // CosmosLayerHelper.swift // // ---------------------------- import UIKit /// Helper class for creating CALayer objects. class CosmosLayerHelper { /** Creates a text layer for the given text string and font. - parameter text: The text shown in the layer. - parameter font: The text font. It is also used to calculate the layer bounds. - parameter color: Text color. - returns: New text layer. */ class func createTextLayer(_ text: String, font: UIFont, color: UIColor) -> CATextLayer { let size = NSString(string: text).size(attributes: [NSFontAttributeName: font]) let layer = CATextLayer() layer.bounds = CGRect(origin: CGPoint(), size: size) layer.anchorPoint = CGPoint() layer.font = CGFont(font.fontName as CFString) layer.fontSize = font.pointSize layer.foregroundColor = color.cgColor layer.contentsScale = UIScreen.main.scale return layer } } // ---------------------------- // // CosmosLayers.swift // // ---------------------------- import UIKit /** Colection of helper functions for creating star layers. */ class CosmosLayers { /** Creates the layers for the stars. - parameter rating: The decimal number representing the rating. Usually a number between 1 and 5 - parameter settings: Star view settings. - returns: Array of star layers. */ class func createStarLayers(_ rating: Double, settings: CosmosSettings) -> [CALayer] { var ratingRemander = CosmosRating.numberOfFilledStars(rating, totalNumberOfStars: settings.totalStars) var starLayers = [CALayer]() for _ in (0..<settings.totalStars) { let fillLevel = CosmosRating.starFillLevel(ratingRemainder: ratingRemander, fillMode: settings.fillMode) let starLayer = createCompositeStarLayer(fillLevel, settings: settings) starLayers.append(starLayer) ratingRemander -= 1 } positionStarLayers(starLayers, starMargin: settings.starMargin) return starLayers } /** Creates an layer that shows a star that can look empty, fully filled or partially filled. Partially filled layer contains two sublayers. - parameter starFillLevel: Decimal number between 0 and 1 describing the star fill level. - parameter settings: Star view settings. - returns: Layer that shows the star. The layer is displauyed in the cosmos view. */ class func createCompositeStarLayer(_ starFillLevel: Double, settings: CosmosSettings) -> CALayer { if starFillLevel >= 1 { return createStarLayer(true, settings: settings) } if starFillLevel == 0 { return createStarLayer(false, settings: settings) } return createPartialStar(starFillLevel, settings: settings) } /** Creates a partially filled star layer with two sub-layers: 1. The layer for the filled star on top. The fill level parameter determines the width of this layer. 2. The layer for the empty star below. - parameter starFillLevel: Decimal number between 0 and 1 describing the star fill level. - parameter settings: Star view settings. - returns: Layer that contains the partially filled star. */ class func createPartialStar(_ starFillLevel: Double, settings: CosmosSettings) -> CALayer { let filledStar = createStarLayer(true, settings: settings) let emptyStar = createStarLayer(false, settings: settings) let parentLayer = CALayer() parentLayer.contentsScale = UIScreen.main.scale parentLayer.bounds = CGRect(origin: CGPoint(), size: filledStar.bounds.size) parentLayer.anchorPoint = CGPoint() parentLayer.addSublayer(emptyStar) parentLayer.addSublayer(filledStar) // make filled layer width smaller according to the fill level. filledStar.bounds.size.width *= CGFloat(starFillLevel) return parentLayer } fileprivate class func createStarLayer(_ isFilled: Bool, settings: CosmosSettings) -> CALayer { let fillColor = isFilled ? settings.filledColor : settings.emptyColor let strokeColor = isFilled ? settings.filledBorderColor : settings.emptyBorderColor return StarLayer.create(settings.starPoints, size: settings.starSize, lineWidth: isFilled ? settings.filledBorderWidth : settings.emptyBorderWidth, fillColor: fillColor, strokeColor: strokeColor) } /** Positions the star layers one after another with a margin in between. - parameter layers: The star layers array. - parameter starMargin: Margin between stars. */ class func positionStarLayers(_ layers: [CALayer], starMargin: Double) { var positionX: CGFloat = 0 for layer in layers { layer.position.x = positionX positionX += layer.bounds.width + CGFloat(starMargin) } } } // ---------------------------- // // CosmosLocalizedRating.swift // // ---------------------------- import Foundation /** Returns the word "Rating" in user's language. It is used for voice-over in accessibility mode. */ struct CosmosLocalizedRating { static var defaultText = "Rating" static var localizedRatings = [ "ar": "تصنيف", "bg": "Рейтинг", "cy": "Sgôr", "da": "Rating", "de": "Bewertung", "el": "Βαθμολογία", "en": defaultText, "es": "Valorar", "et": "Reiting", "fi": "Luokitus", "fr": "De note", "he": "דירוג", "hi": "रेटिंग", "hr": "Ocjena", "hu": "Értékelés", "id": "Peringkat", "it": "Voto", "ko": "등급", "lt": "Reitingas", "lv": "Vērtējums", "nl": "Rating", "no": "Vurdering", "pl": "Ocena", "pt": "Classificação", "ro": "Evaluare", "ru": "Рейтинг", "sk": "Hodnotenie", "sl": "Ocena", "sr": "Рејтинг", "sw": "Rating", "th": "การจัดอันดับ", "tr": "Oy verin", "cs": "Hodnocení", "uk": "Рейтинг", "vi": "Đánh giá", "zh": "评分" ] static var ratingTranslation: String { let languages = preferredLanguages(NSLocale.preferredLanguages) return ratingInPreferredLanguage(languages) } /** Returns the word "Rating" in user's language. - parameter language: ISO 639-1 language code. Example: 'en'. */ static func translation(_ language: String) -> String? { return localizedRatings[language] } /** Returns translation using the preferred language. - parameter preferredLanguages: Array of preferred language codes (ISO 639-1). The first element is most preferred. - parameter localizedText: Dictionary with translations for the languages. The keys are ISO 639-1 language codes and values are the text. - parameter fallbackTranslation: The translation text used if no translation found for the preferred languages. - returns: Translation for the preferred language. */ static func translationInPreferredLanguage(_ preferredLanguages: [String], localizedText: [String: String], fallbackTranslation: String) -> String { for language in preferredLanguages { if let translatedText = translation(language) { return translatedText } } return fallbackTranslation } static func ratingInPreferredLanguage(_ preferredLanguages: [String]) -> String { return translationInPreferredLanguage(preferredLanguages, localizedText: localizedRatings, fallbackTranslation: defaultText) } static func preferredLanguages(_ preferredLocales: [String]) -> [String] { return preferredLocales.map { element in let dashSeparated = element.components(separatedBy: "-") if dashSeparated.count > 1 { return dashSeparated[0] } let underscoreSeparated = element.components(separatedBy: "_") if underscoreSeparated.count > 1 { return underscoreSeparated[0] } return element } } } // ---------------------------- // // CosmosRating.swift // // ---------------------------- import UIKit /** Helper functions for calculating rating. */ struct CosmosRating { /** Returns a decimal number between 0 and 1 describing the star fill level. - parameter ratingRemainder: This value is passed from the loop that creates star layers. The value starts with the rating value and decremented by 1 when each star is created. For example, suppose we want to display rating of 3.5. When the first star is created the ratingRemainder parameter will be 3.5. For the second star it will be 2.5. Third: 1.5. Fourth: 0.5. Fifth: -0.5. - parameter fillMode: Describe how stars should be filled: full, half or precise. - returns: Decimal value between 0 and 1 describing the star fill level. 1 is a fully filled star. 0 is an empty star. 0.5 is a half-star. */ static func starFillLevel(ratingRemainder: Double, fillMode: StarFillMode) -> Double { var result = ratingRemainder if result > 1 { result = 1 } if result < 0 { result = 0 } return roundFillLevel(result, fillMode: fillMode) } /** Rounds a single star's fill level according to the fill mode. "Full" mode returns 0 or 1 by using the standard decimal rounding. "Half" mode returns 0, 0.5 or 1 by rounding the decimal to closest of 3 values. "Precise" mode will return the fill level unchanged. - parameter starFillLevel: Decimal number between 0 and 1 describing the star fill level. - parameter fillMode: Fill mode that is used to round the fill level value. - returns: The rounded fill level. */ static func roundFillLevel(_ starFillLevel: Double, fillMode: StarFillMode) -> Double { switch fillMode { case .full: return Double(round(starFillLevel)) case .half: return Double(round(starFillLevel * 2) / 2) case .precise : return starFillLevel } } /** Helper function for calculating the rating that is displayed to the user taking into account the star fill mode. For example, if the fill mode is .Half and precise rating is 4.6, the displayed rating will be 4.5. And if the fill mode is .Full the displayed rating will be 5. - parameter preciseRating: Precise rating value, like 4.8237 - parameter fillMode: Describe how stars should be filled: full, half or precise. - parameter totalStars: Total number of stars. - returns: Returns rating that is displayed to the user taking into account the star fill mode. */ static func displayedRatingFromPreciseRating(_ preciseRating: Double, fillMode: StarFillMode, totalStars: Int) -> Double { let starFloorNumber = floor(preciseRating) let singleStarRemainder = preciseRating - starFloorNumber var displayedRating = starFloorNumber + starFillLevel( ratingRemainder: singleStarRemainder, fillMode: fillMode) displayedRating = min(Double(totalStars), displayedRating) // Can't go bigger than number of stars displayedRating = max(0, displayedRating) // Can't be less than zero return displayedRating } /** Returns the number of filled stars for given rating. - parameter rating: The rating to be displayed. - parameter totalNumberOfStars: Total number of stars. - returns: Number of filled stars. If rating is biggen than the total number of stars (usually 5) it returns the maximum number of stars. */ static func numberOfFilledStars(_ rating: Double, totalNumberOfStars: Int) -> Double { if rating > Double(totalNumberOfStars) { return Double(totalNumberOfStars) } if rating < 0 { return 0 } return rating } } // ---------------------------- // // CosmosSettings.swift // // ---------------------------- import UIKit /** Settings that define the appearance of the star rating views. */ public struct CosmosSettings { init() {} // MARK: - Star settings // ----------------------------- /// Border color of an empty star. public var emptyBorderColor = CosmosDefaultSettings.emptyBorderColor /// Width of the border for empty star. public var emptyBorderWidth: Double = CosmosDefaultSettings.emptyBorderWidth /// Border color of a filled star. public var filledBorderColor = CosmosDefaultSettings.filledBorderColor /// Width of the border for a filled star. public var filledBorderWidth: Double = CosmosDefaultSettings.filledBorderWidth /// Background color of an empty star. public var emptyColor = CosmosDefaultSettings.emptyColor /// Background color of a filled star. public var filledColor = CosmosDefaultSettings.filledColor /** Defines how the star is filled when the rating value is not a whole integer. It can either show full stars, half stars or stars partially filled according to the rating value. */ public var fillMode = CosmosDefaultSettings.fillMode /// Distance between stars. public var starMargin: Double = CosmosDefaultSettings.starMargin /** Array of points for drawing the star with size of 100 by 100 pixels. Supply your points if you need to draw a different shape. */ public var starPoints: [CGPoint] = CosmosDefaultSettings.starPoints /// Size of a single star. public var starSize: Double = CosmosDefaultSettings.starSize /// The maximum number of stars to be shown. public var totalStars = CosmosDefaultSettings.totalStars // MARK: - Text settings // ----------------------------- /// Color of the text. public var textColor = CosmosDefaultSettings.textColor /// Font for the text. public var textFont = CosmosDefaultSettings.textFont /// Distance between the text and the stars. public var textMargin: Double = CosmosDefaultSettings.textMargin // MARK: - Touch settings // ----------------------------- /// The lowest rating that user can set by touching the stars. public var minTouchRating: Double = CosmosDefaultSettings.minTouchRating /// When `true` the star fill level is updated when user touches the cosmos view. When `false` the Cosmos view only shows the rating and does not act as the input control. public var updateOnTouch = CosmosDefaultSettings.updateOnTouch } // ---------------------------- // // CosmosSize.swift // // ---------------------------- import UIKit /** Helper class for calculating size for the cosmos view. */ class CosmosSize { /** Calculates the size of the cosmos view. It goes through all the star and text layers and makes size the view size is large enough to show all of them. */ class func calculateSizeToFitLayers(_ layers: [CALayer]) -> CGSize { var size = CGSize() for layer in layers { if layer.frame.maxX > size.width { size.width = layer.frame.maxX } if layer.frame.maxY > size.height { size.height = layer.frame.maxY } } return size } } // ---------------------------- // // CosmosText.swift // // ---------------------------- import UIKit /** Positions the text layer to the right of the stars. */ class CosmosText { /** Positions the text layer to the right from the stars. Text is aligned to the center of the star superview vertically. - parameter layer: The text layer to be positioned. - parameter starsSize: The size of the star superview. - parameter textMargin: The distance between the stars and the text. */ class func position(_ layer: CALayer, starsSize: CGSize, textMargin: Double) { layer.position.x = starsSize.width + CGFloat(textMargin) let yOffset = (starsSize.height - layer.bounds.height) / 2 layer.position.y = yOffset } } // ---------------------------- // // CosmosTouch.swift // // ---------------------------- import UIKit /** Functions for working with touch input. */ struct CosmosTouch { /** Calculates the rating based on the touch location. - parameter locationX: The horizontal location of the touch relative to the width of the stars. - parameter starsWidth: The width of the stars excluding the text. - returns: The rating representing the touch location. */ static func touchRating(_ locationX: CGFloat, starsWidth: CGFloat, settings: CosmosSettings) -> Double { let position = locationX / starsWidth let totalStars = Double(settings.totalStars) let actualRating = totalStars * Double(position) var correctedRating = actualRating if settings.fillMode != .precise { correctedRating += 0.25 } correctedRating = CosmosRating.displayedRatingFromPreciseRating(correctedRating, fillMode: settings.fillMode, totalStars: settings.totalStars) correctedRating = max(settings.minTouchRating, correctedRating) // Can't be less than min rating return correctedRating } } // ---------------------------- // // CosmosView.swift // // ---------------------------- import UIKit /** A star rating view that can be used to show customer rating for the products. On can select stars by tapping on them when updateOnTouch settings is true. An optional text can be supplied that is shown on the right side. Example: cosmosView.rating = 4 cosmosView.text = "(123)" Shows: ★★★★☆ (132) */ @IBDesignable open class CosmosView: UIView { /** The currently shown number of stars, usually between 1 and 5. If the value is decimal the stars will be shown according to the Fill Mode setting. */ @IBInspectable open var rating: Double = CosmosDefaultSettings.rating { didSet { if oldValue != rating { update() } } } /// Currently shown text. Set it to nil to display just the stars without text. @IBInspectable open var text: String? { didSet { if oldValue != text { update() } } } /// Star rating settings. open var settings = CosmosSettings() { didSet { update() } } /// Stores calculated size of the view. It is used as intrinsic content size. fileprivate var viewSize = CGSize() /// Draws the stars when the view comes out of storyboard with default settings open override func awakeFromNib() { super.awakeFromNib() update() } /** Initializes and returns a newly allocated cosmos view object. */ convenience public init() { self.init(frame: CGRect()) } /** Initializes and returns a newly allocated cosmos view object with the specified frame rectangle. - parameter frame: The frame rectangle for the view. */ override public init(frame: CGRect) { super.init(frame: frame) update() self.frame.size = intrinsicContentSize improvePerformance() } /// Initializes and returns a newly allocated cosmos view object. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) improvePerformance() } /// Change view settings for faster drawing fileprivate func improvePerformance() { /// Cache the view into a bitmap instead of redrawing the stars each time layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale isOpaque = true } /** Updates the stars and optional text based on current values of `rating` and `text` properties. */ open func update() { // Create star layers // ------------ var layers = CosmosLayers.createStarLayers(rating, settings: settings) layer.sublayers = layers // Create text layer // ------------ if let text = text { let textLayer = createTextLayer(text, layers: layers) layers.append(textLayer) } // Update size // ------------ updateSize(layers) // Update accesibility // ------------ updateAccessibility() } /** Creates the text layer for the given text string. - parameter text: Text string for the text layer. - parameter layers: Arrays of layers containing the stars. - returns: The newly created text layer. */ fileprivate func createTextLayer(_ text: String, layers: [CALayer]) -> CALayer { let textLayer = CosmosLayerHelper.createTextLayer(text, font: settings.textFont, color: settings.textColor) let starsSize = CosmosSize.calculateSizeToFitLayers(layers) CosmosText.position(textLayer, starsSize: starsSize, textMargin: settings.textMargin) layer.addSublayer(textLayer) return textLayer } /** Updates the size to fit all the layers containing stars and text. - parameter layers: Array of layers containing stars and the text. */ fileprivate func updateSize(_ layers: [CALayer]) { viewSize = CosmosSize.calculateSizeToFitLayers(layers) invalidateIntrinsicContentSize() } /// Returns the content size to fit all the star and text layers. override open var intrinsicContentSize: CGSize { return viewSize } // MARK: - Accessibility fileprivate func updateAccessibility() { CosmosAccessibility.update(self, rating: rating, text: text, settings: settings) } /// Called by the system in accessibility voice-over mode when the value is incremented by the user. open override func accessibilityIncrement() { super.accessibilityIncrement() rating += CosmosAccessibility.accessibilityIncrement(rating, settings: settings) didTouchCosmos?(rating) didFinishTouchingCosmos?(rating) } /// Called by the system in accessibility voice-over mode when the value is decremented by the user. open override func accessibilityDecrement() { super.accessibilityDecrement() rating -= CosmosAccessibility.accessibilityDecrement(rating, settings: settings) didTouchCosmos?(rating) didFinishTouchingCosmos?(rating) } // MARK: - Touch recognition /// Closure will be called when user touches the cosmos view. The touch rating argument is passed to the closure. open var didTouchCosmos: ((Double)->())? /// Closure will be called when the user lifts finger from the cosmos view. The touch rating argument is passed to the closure. open var didFinishTouchingCosmos: ((Double)->())? /// Overriding the function to detect the first touch gesture. open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) if let touch = touches.first { let location = touch.location(in: self).x onDidTouch(location, starsWidth: widthOfStars) } } /// Overriding the function to detect touch move. open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) if let touch = touches.first { let location = touch.location(in: self).x onDidTouch(location, starsWidth: widthOfStars) } } /// Detecting event when the user lifts their finger. open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) didFinishTouchingCosmos?(rating) } /** Called when the view is touched. - parameter locationX: The horizontal location of the touch relative to the width of the stars. - parameter starsWidth: The width of the stars excluding the text. */ func onDidTouch(_ locationX: CGFloat, starsWidth: CGFloat) { let calculatedTouchRating = CosmosTouch.touchRating(locationX, starsWidth: starsWidth, settings: settings) if settings.updateOnTouch { rating = calculatedTouchRating } if calculatedTouchRating == previousRatingForDidTouchCallback { // Do not call didTouchCosmos if rating has not changed return } didTouchCosmos?(calculatedTouchRating) previousRatingForDidTouchCallback = calculatedTouchRating } fileprivate var previousRatingForDidTouchCallback: Double = -123.192 /// Width of the stars (excluding the text). Used for calculating touch location. var widthOfStars: CGFloat { if let sublayers = self.layer.sublayers , settings.totalStars <= sublayers.count { let starLayers = Array(sublayers[0..<settings.totalStars]) return CosmosSize.calculateSizeToFitLayers(starLayers).width } return 0 } /// Increase the hitsize of the view if it's less than 44px for easier touching. override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let oprimizedBounds = CosmosTouchTarget.optimize(bounds) return oprimizedBounds.contains(point) } // MARK: - Properties inspectable from the storyboard @IBInspectable var totalStars: Int = CosmosDefaultSettings.totalStars { didSet { settings.totalStars = totalStars } } @IBInspectable var starSize: Double = CosmosDefaultSettings.starSize { didSet { settings.starSize = starSize } } @IBInspectable var filledColor: UIColor = CosmosDefaultSettings.filledColor { didSet { settings.filledColor = filledColor } } @IBInspectable var emptyColor: UIColor = CosmosDefaultSettings.emptyColor { didSet { settings.emptyColor = emptyColor } } @IBInspectable var emptyBorderColor: UIColor = CosmosDefaultSettings.emptyBorderColor { didSet { settings.emptyBorderColor = emptyBorderColor } } @IBInspectable var emptyBorderWidth: Double = CosmosDefaultSettings.emptyBorderWidth { didSet { settings.emptyBorderWidth = emptyBorderWidth } } @IBInspectable var filledBorderColor: UIColor = CosmosDefaultSettings.filledBorderColor { didSet { settings.filledBorderColor = filledBorderColor } } @IBInspectable var filledBorderWidth: Double = CosmosDefaultSettings.filledBorderWidth { didSet { settings.filledBorderWidth = filledBorderWidth } } @IBInspectable var starMargin: Double = CosmosDefaultSettings.starMargin { didSet { settings.starMargin = starMargin } } @IBInspectable var fillMode: Int = CosmosDefaultSettings.fillMode.rawValue { didSet { settings.fillMode = StarFillMode(rawValue: fillMode) ?? CosmosDefaultSettings.fillMode } } @IBInspectable var textSize: Double = CosmosDefaultSettings.textSize { didSet { settings.textFont = settings.textFont.withSize(CGFloat(textSize)) } } @IBInspectable var textMargin: Double = CosmosDefaultSettings.textMargin { didSet { settings.textMargin = textMargin } } @IBInspectable var textColor: UIColor = CosmosDefaultSettings.textColor { didSet { settings.textColor = textColor } } @IBInspectable var updateOnTouch: Bool = CosmosDefaultSettings.updateOnTouch { didSet { settings.updateOnTouch = updateOnTouch } } @IBInspectable var minTouchRating: Double = CosmosDefaultSettings.minTouchRating { didSet { settings.minTouchRating = minTouchRating } } /// Draw the stars in interface buidler open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() update() } } // ---------------------------- // // CosmosTouchTarget.swift // // ---------------------------- import UIKit /** Helper function to make sure bounds are big enought to be used as touch target. The function is used in pointInside(point: CGPoint, withEvent event: UIEvent?) of UIImageView. */ struct CosmosTouchTarget { static func optimize(_ bounds: CGRect) -> CGRect { let recommendedHitSize: CGFloat = 44 var hitWidthIncrease: CGFloat = recommendedHitSize - bounds.width var hitHeightIncrease: CGFloat = recommendedHitSize - bounds.height if hitWidthIncrease < 0 { hitWidthIncrease = 0 } if hitHeightIncrease < 0 { hitHeightIncrease = 0 } let extendedBounds: CGRect = bounds.insetBy(dx: -hitWidthIncrease / 2, dy: -hitHeightIncrease / 2) return extendedBounds } } // ---------------------------- // // StarFillMode.swift // // ---------------------------- import Foundation /** Defines how the star is filled when the rating is not an integer number. For example, if rating is 4.6 and the fill more is Half, the star will appear to be half filled. */ public enum StarFillMode: Int { /// Show only fully filled stars. For example, fourth star will be empty for 3.2. case full = 0 /// Show fully filled and half-filled stars. For example, fourth star will be half filled for 3.6. case half = 1 /// Fill star according to decimal rating. For example, fourth star will be 20% filled for 3.2. case precise = 2 } // ---------------------------- // // StarLayer.swift // // ---------------------------- import UIKit /** Creates a layer with a single star in it. */ struct StarLayer { /** Creates a square layer with given size and draws the star shape in it. - parameter starPoints: Array of points for drawing a closed shape. The size of enclosing rectangle is 100 by 100. - parameter size: The width and height of the layer. The star shape is scaled to fill the size of the layer. - parameter lineWidth: The width of the star stroke. - parameter fillColor: Star shape fill color. Fill color is invisible if it is a clear color. - parameter strokeColor: Star shape stroke color. Stroke is invisible if it is a clear color. - returns: New layer containing the star shape. */ static func create(_ starPoints: [CGPoint], size: Double, lineWidth: Double, fillColor: UIColor, strokeColor: UIColor) -> CALayer { let containerLayer = createContainerLayer(size) let path = createStarPath(starPoints, size: size, lineWidth: lineWidth) let shapeLayer = createShapeLayer(path.cgPath, lineWidth: lineWidth, fillColor: fillColor, strokeColor: strokeColor, size: size) containerLayer.addSublayer(shapeLayer) return containerLayer } /** Creates the star shape layer. - parameter path: The star shape path. - parameter lineWidth: The width of the star stroke. - parameter fillColor: Star shape fill color. Fill color is invisible if it is a clear color. - parameter strokeColor: Star shape stroke color. Stroke is invisible if it is a clear color. - returns: New shape layer. */ static func createShapeLayer(_ path: CGPath, lineWidth: Double, fillColor: UIColor, strokeColor: UIColor, size: Double) -> CALayer { let layer = CAShapeLayer() layer.anchorPoint = CGPoint() layer.contentsScale = UIScreen.main.scale layer.strokeColor = strokeColor.cgColor layer.fillColor = fillColor.cgColor layer.lineWidth = CGFloat(lineWidth) layer.bounds.size = CGSize(width: size, height: size) layer.masksToBounds = true layer.path = path layer.isOpaque = true return layer } /** Creates a layer that will contain the shape layer. - returns: New container layer. */ static func createContainerLayer(_ size: Double) -> CALayer { let layer = CALayer() layer.contentsScale = UIScreen.main.scale layer.anchorPoint = CGPoint() layer.masksToBounds = true layer.bounds.size = CGSize(width: size, height: size) layer.isOpaque = true return layer } /** Creates a path for the given star points and size. The star points specify a shape of size 100 by 100. The star shape will be scaled if the size parameter is not 100. For exampe, if size parameter is 200 the shape will be scaled by 2. - parameter starPoints: Array of points for drawing a closed shape. The size of enclosing rectangle is 100 by 100. - parameter size: Specifies the size of the shape to return. - returns: New shape path. */ static func createStarPath(_ starPoints: [CGPoint], size: Double, lineWidth: Double) -> UIBezierPath { let lineWidthLocal = lineWidth + ceil(lineWidth * 0.3) let sizeWithoutLineWidth = size - lineWidthLocal * 2 let points = scaleStar(starPoints, factor: sizeWithoutLineWidth / 100, lineWidth: lineWidthLocal) let path = UIBezierPath() path.move(to: points[0]) let remainingPoints = Array(points[1..<points.count]) for point in remainingPoints { path.addLine(to: point) } path.close() return path } /** Scale the star points by the given factor. - parameter starPoints: Array of points for drawing a closed shape. The size of enclosing rectangle is 100 by 100. - parameter factor: The factor by which the star points are scaled. For example, if it is 0.5 the output points will define the shape twice as small as the original. - returns: The scaled shape. */ static func scaleStar(_ starPoints: [CGPoint], factor: Double, lineWidth: Double) -> [CGPoint] { return starPoints.map { point in return CGPoint( x: point.x * CGFloat(factor) + CGFloat(lineWidth), y: point.y * CGFloat(factor) + CGFloat(lineWidth) ) } } }
7d5c55ac881dded61c9d8130a368c03b
26.412312
381
0.681786
false
false
false
false
doo/das-quadrat
refs/heads/develop
Source/Shared/Request.swift
bsd-2-clause
1
// // Request.swift // Quadrat // // Created by Constantine Fry on 17/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation class Request { /** Request parameters. */ let parameters : Parameters? /** Endpoint path. */ let path : String /** HTTP method. POST or GET. */ let HTTPMethod : String /** Sessian wise parameters from configuration. */ let sessionParameters : Parameters /** Should be like this "https://api.foursquare.com/v2". Specified in `Configuration` */ let baseURL : NSURL /** The timeout interval in seconds. */ var timeoutInterval : NSTimeInterval = 60 init(baseURL:NSURL, path: String, parameters: Parameters?, sessionParameters:Parameters, HTTPMethod: String) { self.baseURL = baseURL self.parameters = parameters self.sessionParameters = sessionParameters self.HTTPMethod = HTTPMethod self.path = path } func URLRequest() -> NSURLRequest { var allParameters = self.sessionParameters if parameters != nil { allParameters += parameters! } let URL = self.baseURL.URLByAppendingPathComponent(self.path) let requestURL = Parameter.buildURL(URL, parameters: allParameters) let request = NSMutableURLRequest(URL: requestURL) request.HTTPMethod = HTTPMethod return request } }
a6b0c084fb7e40a9019e8bbf1d8bcdb3
29.510204
114
0.621405
false
false
false
false
alblue/swift
refs/heads/master
test/SILGen/protocol_optional.swift
apache-2.0
1
// RUN: %target-swift-emit-silgen -module-name protocol_optional -parse-as-library -disable-objc-attr-requires-foundation-module -enable-objc-interop -enable-sil-ownership %s | %FileCheck %s @objc protocol P1 { @objc optional func method(_ x: Int) @objc optional var prop: Int { get } @objc optional subscript (i: Int) -> Int { get } } // CHECK-LABEL: sil hidden @$s17protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF : $@convention(thin) <T where T : P1> (@guaranteed T) -> () func optionalMethodGeneric<T : P1>(t t : T) { var t = t // CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T): // CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T> // CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]] // CHECK: [[T_COPY:%.*]] = copy_value [[T]] // CHECK: store [[T_COPY]] to [init] [[PT]] : $*T // CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed (Int) -> ()> } // CHECK: project_box [[OPT_BOX]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T // CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T // CHECK: alloc_stack $Optional<@callee_guaranteed (Int) -> ()> // CHECK: dynamic_method_br [[T]] : $T, #P1.method!1.foreign var methodRef = t.method } // CHECK: } // end sil function '$s17protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF' // CHECK-LABEL: sil hidden @$s17protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@guaranteed T) -> () func optionalPropertyGeneric<T : P1>(t t : T) { var t = t // CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T): // CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T> // CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]] // CHECK: [[T_COPY:%.*]] = copy_value [[T]] // CHECK: store [[T_COPY]] to [init] [[PT]] : $*T // CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> } // CHECK: project_box [[OPT_BOX]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T // CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T // CHECK: alloc_stack $Optional<Int> // CHECK: dynamic_method_br [[T]] : $T, #P1.prop!getter.1.foreign var propertyRef = t.prop } // CHECK: } // end sil function '$s17protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden @$s17protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@guaranteed T) -> () func optionalSubscriptGeneric<T : P1>(t t : T) { var t = t // CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T): // CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T> // CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]] // CHECK: [[T_COPY:%.*]] = copy_value [[T]] // CHECK: store [[T_COPY]] to [init] [[PT]] : $*T // CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> } // CHECK: project_box [[OPT_BOX]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T // CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T // CHECK: [[INT64:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[FIVELIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 5 // CHECK: [[INTCONV:%[0-9]+]] = function_ref @$sSi2{{[_0-9a-zA-Z]*}}fC // CHECK: [[FIVE:%[0-9]+]] = apply [[INTCONV]]([[FIVELIT]], [[INT64]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: alloc_stack $Optional<Int> // CHECK: dynamic_method_br [[T]] : $T, #P1.subscript!getter.1.foreign var subscriptRef = t[5] } // CHECK: } // end sil function '$s17protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F'
b691f3dda261cc2de319a26bd706f09e
52.558824
190
0.565898
false
false
false
false
Railsreactor/json-data-sync-swift
refs/heads/master
JDSKit/Core/EntityService.swift
mit
1
// // EntityService.swift // JDSKit // // Created by Igor Reshetnikov on 12/8/15. // Copyright © 2015 RailsReactor. All rights reserved. // import Foundation import PromiseKit import CocoaLumberjack open class EntityService: CoreService { open var entityType: ManagedEntity.Type public required init (entityType: ManagedEntity.Type) { self.entityType = entityType } open class func sharedService<T: ManagedEntity>(_ entityType: T.Type = T.self) -> EntityService { return AbstractRegistryService.mainRegistryService.entityService(entityType) } open func entityGateway() -> GenericEntityGateway? { return self.localManager.entityGatewayByEntityType(self.entityType) } fileprivate func cachedEntity(_ inputQuery: String = "", arguments: [Any]? = nil, sortKeys: [String]? = nil) -> [ManagedEntity] { let descriptors: [NSSortDescriptor] = sortKeys?.sortDescriptors() ?? [NSSortDescriptor(key: "createDate", ascending: false)] var query = inputQuery if !query.isEmpty { query += " && " } query += "isLoaded == true && pendingDelete != true" do { if let entitiyGateway = self.entityGateway() { let entities = try entitiyGateway.fetchEntities(query, arguments: (arguments ?? [Any]()), sortDescriptors: descriptors) as [ManagedEntity] return entities } } catch { DDLogDebug("Failed to fetch cars: \(error)") } return [ManagedEntity]() } open func syncEntityInternal(_ query: String = "", arguments: [Any]? = nil, remoteFilters: [NSComparisonPredicate]?=nil, includeRelations: [String]?=nil) -> Promise<Void> { return self.remoteManager.loadEntities(self.entityType, filters: remoteFilters, include: includeRelations).then(on: .global()) { (input) -> Promise<Void> in return self.runOnBackgroundContext { () -> Void in let start = NSDate() DDLogDebug("Will Insert \(input.count) Entities of type: \(String(describing: self.entityType))" ) if let entityGateway = self.entityGateway() { let newItems: [ManagedEntity] = try entityGateway.insertEnities(input, isFirstInsert: false) ?? [] DDLogDebug("Did Insert \(newItems.count) Entities of type: \(String(describing: self.entityType)) Time Spent: \(abs(start.timeIntervalSinceNow))" ) } else { DDLogDebug("No gateway for Entities of type: \(String(describing: self.entityType)). Skipped. Time Spent: \(abs(start.timeIntervalSinceNow))" ) } } } } open func syncEntityDelta(_ updateDate: Date?) -> Promise<Void> { return Promise<Void>(value:()).then(on: .global()) { _ -> Promise<Void> in if self.trySync() { var predicates: [NSComparisonPredicate]? = nil if updateDate != nil { predicates = [NSComparisonPredicate(format: "updated_at_gt == %@", optionals: [updateDate!.toSystemString()])] } DDLogDebug("Will download \(self.entityType) Delta From: \(updateDate)") return self.syncEntityInternal("", arguments: nil, remoteFilters: predicates, includeRelations: nil).always { self.endSync() } } else { self.waitForSync() return Promise<Void>(value:()) } } } open func syncEntity(_ query: String = "", arguments: [Any]? = nil, remoteFilters: [NSComparisonPredicate]?=nil, includeRelations: [String]?=nil, includeEntities: [ManagedEntity.Type]?=nil, skipSave: Bool = false) -> Promise<Void> { var promiseChain = Promise<Void>(value:()) if includeEntities != nil { for type in includeEntities! { let includeService = AbstractRegistryService.mainRegistryService.entityService(type) promiseChain = promiseChain.then(on: .global()) { return includeService.syncEntity("", arguments: nil, remoteFilters: nil, includeRelations: nil, includeEntities: nil, skipSave: true) } } } return promiseChain.then(on: .global()) { _ -> Promise<Void> in if self.trySync() { return self.syncEntityInternal(query, arguments: arguments, remoteFilters: remoteFilters, includeRelations: includeRelations).then(on: .global()) { () -> Void in if !skipSave { self.localManager.saveSyncSafe() } }.always { self.endSync() } } else { self.waitForSync() return Promise<Void>(value:()) } } } fileprivate func refreshEntity(_ entity: ManagedEntity, includeRelations: [String]?=nil) -> Promise<Void> { guard let id = entity.id else { return Promise(error: CoreError.runtimeError(description: "Entity must have an id", cause: nil)) } let predicate = NSComparisonPredicate(format: "id_eq == \(id)", optionals: nil) return self.remoteManager.loadEntities(self.entityType, filters: [predicate], include: includeRelations).then(on: .global()) { entities -> Promise<Void> in return self.runOnBackgroundContext { if let entity = entities.first { try self.entityGateway()?.insertEntity(entity) } self.localManager.saveSyncSafe() } } } //MARK: - Other fileprivate func saveEntity(_ entity: ManagedEntity) -> Promise<ManagedEntity> { return self.remoteManager.saveEntity(entity).then(on: .global()) { (remoteEntity) -> Promise<Container> in return self.runOnBackgroundContext { () -> Container in let result = try self.entityGateway()?.insertEntity(remoteEntity) ?? remoteEntity self.localManager.saveBackgroundUnsafe() return result.objectContainer() } }.then { (container) -> ManagedEntity in let entity = try (container.containedObject()! as ManagedEntity) entity.refresh() return entity } } fileprivate func deleteEntity(_ entity: ManagedEntity) -> Promise<Void> { entity.pendingDelete = true let countainer = entity.objectContainer() return self.remoteManager.deleteEntity(entity).recover { (error) -> Void in switch error { case CoreError.serviceError(_, _): return default: entity.pendingDelete = nil throw error } }.thenInBGContext { () -> Void in try self.entityGateway()?.deleteEntity(countainer.containedObject()!) self.localManager.saveBackgroundUnsafe() } } fileprivate func createBlankEntity() -> ManagedEntity { let dummyClass: DummyManagedEntity.Type = ModelRegistry.sharedRegistry.extractRep(entityType, subclassOf: DummyManagedEntity.self) as! DummyManagedEntity.Type return dummyClass.init() } fileprivate func patchEntity(_ entity: ManagedEntity, applyPatch: (_ entity: ManagedEntity) -> Void ) -> Promise<ManagedEntity> { let patch: ManagedEntity = self.createBlankEntity() patch.id = entity.id! applyPatch(patch) return self.remoteManager.saveEntity(patch).thenInBGContext { (remoteEntity) -> Container in let result = try self.entityGateway()?.insertEntity(remoteEntity) ?? remoteEntity self.localManager.saveBackgroundUnsafe() return result.objectContainer() }.then { (container) -> ManagedEntity in let entity = try (container.containedObject()! as ManagedEntity) entity.refresh() return entity } } fileprivate func createOrUpdate(_ entity: ManagedEntity, updateClosure: ((_ entity: ManagedEntity) -> Void)? = nil) -> Promise<ManagedEntity> { if entity.isTemp() { if updateClosure != nil { updateClosure!(entity) } return saveEntity(entity) } else { return patchEntity(entity, applyPatch: updateClosure! ) } } } open class GenericService<T: ManagedEntity>: EntityService { public required init() { super.init(entityType: T.self) } public required init(entityType: ManagedEntity.Type) { fatalError("init(entityType:) has not been implemented") } open class func sharedService() -> GenericService<T> { return AbstractRegistryService.mainRegistryService.entityService() } open func cachedEntity(_ query: String = "", arguments: [Any]? = nil, sortKeys: [String]?=nil) -> [T] { return super.cachedEntity(query, arguments: arguments, sortKeys: sortKeys) as! [T] } open func createOrUpdate(_ entity: T, updateClosure: ((_ entity: T) -> Void)? = nil) -> Promise<T> { return super.createOrUpdate(entity, updateClosure: updateClosure != nil ? { updateClosure!($0 as! T) } : nil).then { $0 as! T } } open func refreshEntity(_ entity: T, includeRelations: [String]?=nil) -> Promise<Void> { return super.refreshEntity(entity, includeRelations: includeRelations) } open func deleteEntity(_ entity: T) -> Promise<Void> { return super.deleteEntity(entity) } open func createBlankEntity() -> T { return super.createBlankEntity() as! T } }
fb3cdb56c2ceb77d0cfa2fc07e74df9b
40.493724
236
0.594535
false
false
false
false
massimoksi/Shine
refs/heads/master
Shine/SettingsFormViewController.swift
mit
1
// Copyright (c) 2015 Massimo Peri (@massimoksi) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Former final class SettingsFormViewController: FormViewController { // MARK: Properties weak var delegate: SettingsFormViewDelegate? private lazy var timerDurationFormatter: NSDateComponentsFormatter = { let formatter = NSDateComponentsFormatter() formatter.unitsStyle = .Abbreviated return formatter }() private var timerDurationLabelRow: LabelRowFormer<FormLabelCell>! // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() let createHeader: (String -> ViewFormer) = { text in return LabelViewFormer<FormLabelHeaderView>().configure { $0.text = text.uppercaseString $0.viewHeight = 42.0 } } // ------------------------- // Light // ------------------------- let colorSelectionRow = CustomRowFormer<ColorSelectionCell>(instantiateType: .Nib(nibName: "ColorSelectionCell")) { $0.collectionView.dataSource = self $0.collectionView.delegate = self }.configure { $0.rowHeight = 54.0 } let colorSection = SectionFormer(rowFormer: colorSelectionRow).set(headerViewFormer: createHeader(NSLocalizedString("SETTINGS_SEC_LIGHT", comment: ""))) // ------------------------- // Turn off // ------------------------- let doubleTapSwitchRow = SwitchRowFormer<FormSwitchCell>() { $0.titleLabel.text = NSLocalizedString("SETTINGS_ROW_DOUBLE_TAP", comment: "") }.configure { $0.switched = Settings.doubleTap } let timerEnableSwitchRow = SwitchRowFormer<FormSwitchCell>() { $0.titleLabel.text = NSLocalizedString("SETTINGS_ROW_TIMER_ENABLE", comment: "") }.configure { $0.switched = Settings.timerEnable } timerDurationLabelRow = LabelRowFormer<FormLabelCell>().configure { $0.text = NSLocalizedString("SETTINGS_ROW_TIMER_DURATION", comment: "") let comps = NSDateComponents() let timerDuration = Settings.timerDuration comps.hour = Int(timerDuration) / 3600 comps.minute = (Int(timerDuration) % 3600) / 60 $0.subText = timerDurationFormatter.stringFromDateComponents(comps) } let timerDurationPickerRow = CustomRowFormer<CountDownCell>(instantiateType: .Nib(nibName: "CountDownCell")) { row in // Workaround to a bug in UIDatePicker implementaion. // http://stackoverflow.com/questions/20181980/uidatepicker-bug-uicontroleventvaluechanged-after-hitting-minimum-internal dispatch_async(dispatch_get_main_queue(), { row.countDownPicker.countDownDuration = Settings.timerDuration }) row.countDownPicker.addTarget(self, action: #selector(SettingsFormViewController.updateTimerDuration(_:)), forControlEvents: .ValueChanged) }.configure { $0.rowHeight = 217.0 } let lockScreenSwitchRow = SwitchRowFormer<FormSwitchCell>() { $0.titleLabel.text = NSLocalizedString("SETTINGS_ROW_LOCK_SCREEN", comment: "") }.configure { $0.switched = Settings.lockScreen }.onSwitchChanged { switched in Settings.lockScreen = switched } let monitorBatterySwitchRow = SwitchRowFormer<FormSwitchCell>() { $0.titleLabel.text = NSLocalizedString("SETTINGS_ROW_MONITOR_BATTERY", comment: "") }.configure { $0.switched = Settings.monitorBattery }.onSwitchChanged { switched in Settings.monitorBattery = switched } var turnOffRows: [RowFormer] if Settings.timerEnable { turnOffRows = [doubleTapSwitchRow, timerEnableSwitchRow, timerDurationLabelRow, lockScreenSwitchRow, monitorBatterySwitchRow] } else if Settings.doubleTap { turnOffRows = [doubleTapSwitchRow, timerEnableSwitchRow, lockScreenSwitchRow, monitorBatterySwitchRow] } else { turnOffRows = [doubleTapSwitchRow, timerEnableSwitchRow, monitorBatterySwitchRow] } let turnOffSection = SectionFormer(rowFormers: turnOffRows).set(headerViewFormer: createHeader(NSLocalizedString("SETTINGS_SEC_TURN_OFF", comment: ""))) doubleTapSwitchRow.onSwitchChanged { [unowned self] switched in Settings.doubleTap = switched if switched { // Insert lock screen row if not yet visible. if !Settings.timerEnable { self.former.insertUpdate(rowFormer: lockScreenSwitchRow, below: timerEnableSwitchRow, rowAnimation: .Automatic) } } else { // Remove lock screen row only if timer is not enabled. if !Settings.timerEnable { self.former.removeUpdate(rowFormer: lockScreenSwitchRow, rowAnimation: .Automatic) } } } timerEnableSwitchRow.onSwitchChanged { [unowned self] switched in Settings.timerEnable = switched if switched { self.former.insertUpdate(rowFormer: self.timerDurationLabelRow, toIndexPath: NSIndexPath(forItem: 2, inSection: 1), rowAnimation: .Automatic) self.delegate?.timerWasEnabled() self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 1), atScrollPosition: .Bottom, animated: true) // Insert lock screen row if not yet visible. if !Settings.doubleTap { self.former.insertUpdate(rowFormer: lockScreenSwitchRow, below: self.timerDurationLabelRow, rowAnimation: .Automatic) } } else { // Remove lock screen row only if double tap is disabled. let rowFormersToBeRemoved = Settings.doubleTap ? [self.timerDurationLabelRow, timerDurationPickerRow] : [self.timerDurationLabelRow, timerDurationPickerRow, lockScreenSwitchRow] self.former.removeUpdate(rowFormers: rowFormersToBeRemoved, rowAnimation: .Automatic) self.delegate?.timerWasDisabled() } } var pickerVisible = false timerDurationLabelRow.onSelected { [unowned self] row in if !pickerVisible { self.former.deselect(true) self.former.insertUpdate(rowFormer: timerDurationPickerRow, below: row, rowAnimation: .Automatic) pickerVisible = true self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 1), atScrollPosition: .Bottom, animated: true) } else { self.former.deselect(true) self.former.removeUpdate(rowFormer: timerDurationPickerRow, rowAnimation: .Automatic) pickerVisible = false } } former.append(sectionFormer: colorSection, turnOffSection) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Actions func updateTimerDuration(sender: UIDatePicker) { Settings.timerDuration = sender.countDownDuration timerDurationLabelRow.update { row in let comps = NSDateComponents() let timerDuration = sender.countDownDuration comps.hour = Int(timerDuration) / 3600 comps.minute = (Int(timerDuration) % 3600) / 60 row.subText = timerDurationFormatter.stringFromDateComponents(comps) } delegate?.timerDidChange() } } // MARK: - Collection view data source extension SettingsFormViewController: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return LightColor.allColors.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ColorSelectionCheckbox", forIndexPath: indexPath) as! ColorSelectionCheckbox cell.tintColor = LightColor.allColors[indexPath.item] cell.on = Settings.lightColor == indexPath.item return cell } } // MARK: - Collection view delegate extension SettingsFormViewController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let selectedColor = indexPath.item if selectedColor != Settings.lightColor { let oldCell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: Settings.lightColor, inSection: 0)) as! ColorSelectionCheckbox oldCell.on = false Settings.lightColor = selectedColor let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ColorSelectionCheckbox cell.on = true delegate?.colorDidChange() } } } // MARK: - Protocols protocol SettingsFormViewDelegate: class { func colorDidChange() func timerWasEnabled() func timerWasDisabled() func timerDidChange() }
72247bb4a43c05abcf8969b031aec964
39.691406
193
0.658731
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Kickstarter-iOS/Features/PledgeView/Controllers/PledgeViewController.swift
apache-2.0
1
import KsApi import Library import PassKit import Prelude import Stripe import UIKit private enum Layout { enum Style { static let cornerRadius: CGFloat = Styles.grid(2) static let modalHeightMultiplier: CGFloat = 0.65 } enum Margin { static let topBottom: CGFloat = Styles.grid(3) static let leftRight: CGFloat = CheckoutConstants.PledgeView.Inset.leftRight } } protocol PledgeViewControllerDelegate: AnyObject { func pledgeViewControllerDidUpdatePledge(_ viewController: PledgeViewController, message: String) } protocol PaymentSheetAppearanceDelegate: AnyObject { func pledgeViewControllerPaymentSheet(_ viewController: PledgeViewController, hidden: Bool) } final class PledgeViewController: UIViewController, MessageBannerViewControllerPresenting, ProcessingViewPresenting { // MARK: - Properties private lazy var confirmationSectionViews = { [self.pledgeDisclaimerView] }() public weak var delegate: PledgeViewControllerDelegate? public weak var paymentSheetAppearanceDelegate: PaymentSheetAppearanceDelegate? private lazy var descriptionSectionSeparator: UIView = { UIView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() private lazy var projectTitleLabel = UILabel(frame: .zero) private lazy var sectionSeparatorViews = { [self.descriptionSectionSeparator, self.summarySectionSeparator] }() private lazy var summarySectionSeparator: UIView = { UIView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() private lazy var pledgeAmountViewController = { PledgeAmountViewController.instantiate() |> \.delegate .~ self }() internal var processingView: ProcessingView? = ProcessingView(frame: .zero) private lazy var pledgeDisclaimerView: PledgeDisclaimerView = { PledgeDisclaimerView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false |> \.delegate .~ self }() private lazy var descriptionSectionViews = { [self.projectTitleLabel, self.descriptionSectionSeparator] }() private lazy var pledgeExpandableRewardsHeaderViewController = { PledgeExpandableRewardsHeaderViewController(nibName: nil, bundle: nil) |> \.animatingViewDelegate .~ self.view }() private lazy var inputsSectionViews = { [ self.shippingLocationViewController.view, self.shippingSummaryView, self.localPickupLocationView, self.pledgeAmountViewController.view ] }() fileprivate lazy var keyboardDimissingTapGestureRecognizer: UITapGestureRecognizer = { UITapGestureRecognizer( target: self, action: #selector(PledgeViewController.dismissKeyboard) ) |> \.cancelsTouchesInView .~ false }() internal var messageBannerViewController: MessageBannerViewController? private lazy var pledgeAmountSummaryViewController: PledgeAmountSummaryViewController = { PledgeAmountSummaryViewController.instantiate() }() private lazy var paymentMethodsSectionViews = { [self.paymentMethodsViewController.view] }() private lazy var paymentMethodsViewController = { PledgePaymentMethodsViewController.instantiate() |> \.messageDisplayingDelegate .~ self |> \.delegate .~ self }() private lazy var shippingLocationViewController = { PledgeShippingLocationViewController.instantiate() |> \.delegate .~ self }() private lazy var localPickupLocationView = { PledgeLocalPickupView(frame: .zero) }() private lazy var shippingSummaryView: PledgeShippingSummaryView = { PledgeShippingSummaryView(frame: .zero) }() private lazy var summarySectionViews = { [ self.summarySectionSeparator, self.summaryViewController.view ] }() private lazy var summaryViewController = { PledgeSummaryViewController.instantiate() }() private lazy var pledgeCTAContainerView: PledgeViewCTAContainerView = { PledgeViewCTAContainerView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false |> \.delegate .~ self }() private lazy var rootScrollView: UIScrollView = { UIScrollView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() private lazy var rootStackView: UIStackView = { UIStackView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() private lazy var rootInsetStackView: UIStackView = { UIStackView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() private var sessionStartedObserver: Any? private let viewModel: PledgeViewModelType = PledgeViewModel() // MARK: - Lifecycle func configure(with data: PledgeViewData) { self.viewModel.inputs.configure(with: data) } override func viewDidLoad() { super.viewDidLoad() _ = self |> \.extendedLayoutIncludesOpaqueBars .~ true self.messageBannerViewController = self.configureMessageBannerViewController(on: self) self.view.addGestureRecognizer(self.keyboardDimissingTapGestureRecognizer) self.configureChildViewControllers() self.configureDisclaimerView() self.setupConstraints() self.viewModel.inputs.viewDidLoad() } deinit { self.sessionStartedObserver.doIfSome(NotificationCenter.default.removeObserver) } // MARK: - Configuration private func configureChildViewControllers() { _ = (self.rootScrollView, self.view) |> ksr_addSubviewToParent() _ = (self.rootStackView, self.rootScrollView) |> ksr_addSubviewToParent() |> ksr_constrainViewToEdgesInParent() _ = (self.pledgeCTAContainerView, self.view) |> ksr_addSubviewToParent() let childViewControllers = [ self.pledgeExpandableRewardsHeaderViewController, self.pledgeAmountSummaryViewController, self.pledgeAmountViewController, self.shippingLocationViewController, self.summaryViewController, self.paymentMethodsViewController ] let arrangedSubviews = [ self.pledgeExpandableRewardsHeaderViewController.view, self.rootInsetStackView ] .compact() let arrangedInsetSubviews = [ self.descriptionSectionViews, [self.pledgeAmountSummaryViewController.view], self.inputsSectionViews, self.summarySectionViews, self.paymentMethodsSectionViews, isNativeRiskMessagingControlEnabled() ? self.confirmationSectionViews : [] ] .flatMap { $0 } .compact() arrangedSubviews.forEach { view in self.rootStackView.addArrangedSubview(view) } arrangedInsetSubviews.forEach { view in self.rootInsetStackView.addArrangedSubview(view) } childViewControllers.forEach { viewController in self.addChild(viewController) viewController.didMove(toParent: self) } self.rootStackView .setCustomSpacing(Styles.grid(2), after: self.pledgeExpandableRewardsHeaderViewController.view) } private func setupConstraints() { NSLayoutConstraint.activate([ self.rootScrollView.topAnchor.constraint(equalTo: self.view.topAnchor), self.rootScrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor), self.rootScrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor), self.rootScrollView.bottomAnchor.constraint(equalTo: self.pledgeCTAContainerView.topAnchor), self.pledgeCTAContainerView.leftAnchor.constraint(equalTo: self.view.leftAnchor), self.pledgeCTAContainerView.rightAnchor.constraint(equalTo: self.view.rightAnchor), self.pledgeCTAContainerView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), self.rootStackView.widthAnchor.constraint(equalTo: self.view.widthAnchor) ]) self.sectionSeparatorViews.forEach { view in _ = view.heightAnchor.constraint(equalToConstant: 1) |> \.isActive .~ true view.setContentCompressionResistancePriority(.required, for: .vertical) } } // MARK: - Styles override func bindStyles() { super.bindStyles() _ = self.view |> checkoutBackgroundStyle _ = self.pledgeDisclaimerView |> pledgeDisclaimerViewStyle _ = self.projectTitleLabel |> projectTitleLabelStyle _ = self.rootScrollView |> rootScrollViewStyle _ = self.rootStackView |> rootStackViewStyle _ = self.rootInsetStackView |> rootInsetStackViewStyle _ = self.sectionSeparatorViews ||> separatorStyleDark _ = self.paymentMethodsViewController.view |> roundedStyle(cornerRadius: Layout.Style.cornerRadius) } // MARK: - View model override func bindViewModel() { super.bindViewModel() self.viewModel.outputs.beginSCAFlowWithClientSecret .observeForUI() .observeValues { [weak self] secret in self?.beginSCAFlow(withClientSecret: secret) } self.viewModel.outputs.configureLocalPickupViewWithData .observeForUI() .observeValues { [weak self] data in self?.localPickupLocationView.configure(with: data) } self.viewModel.outputs.configureStripeIntegration .observeForUI() .observeValues { merchantIdentifier, publishableKey in STPAPIClient.shared.publishableKey = publishableKey STPAPIClient.shared.configuration.appleMerchantIdentifier = merchantIdentifier } self.viewModel.outputs.configureShippingLocationViewWithData .observeForUI() .observeValues { [weak self] data in self?.shippingLocationViewController.configureWith(value: data) } self.viewModel.outputs.configureShippingSummaryViewWithData .observeForUI() .observeValues { [weak self] data in self?.shippingSummaryView.configure(with: data) } self.viewModel.outputs.configurePledgeAmountViewWithData .observeForUI() .observeValues { [weak self] data in self?.pledgeAmountViewController.configureWith(value: data) } self.viewModel.outputs.configureExpandableRewardsHeaderWithData .observeForUI() .observeValues { [weak self] data in self?.pledgeExpandableRewardsHeaderViewController.configure(with: data) } self.viewModel.outputs.configurePledgeAmountSummaryViewControllerWithData .observeForUI() .observeValues { [weak self] data in self?.pledgeAmountSummaryViewController.configureWith(data) } self.viewModel.outputs.configurePledgeViewCTAContainerView .observeForUI() .observeValues { [weak self] value in self?.pledgeCTAContainerView.configureWith(value: value) } self.viewModel.outputs.notifyPledgeAmountViewControllerUnavailableAmountChanged .observeForUI() .observeValues { [weak self] amount in self?.pledgeAmountViewController.unavailableAmountChanged(to: amount) } self.viewModel.outputs.configureSummaryViewControllerWithData .observeForUI() .observeValues { [weak self] data in self?.summaryViewController.configure(with: data) } self.viewModel.outputs.configurePaymentMethodsViewControllerWithValue .observeForUI() .observeValues { [weak self] value in self?.paymentMethodsViewController.configure(with: value) self?.paymentSheetAppearanceDelegate = self?.paymentMethodsViewController } self.viewModel.outputs.goToLoginSignup .observeForControllerAction() .observeValues { [weak self] intent, project, reward in self?.goToLoginSignup(with: intent, project: project, reward: reward) } self.sessionStartedObserver = NotificationCenter.default .addObserver(forName: .ksr_sessionStarted, object: nil, queue: nil) { [weak self] _ in self?.viewModel.inputs.userSessionStarted() } self.viewModel.outputs.goToApplePayPaymentAuthorization .observeForControllerAction() .observeValues { [weak self] paymentAuthorizationData in self?.goToPaymentAuthorization(paymentAuthorizationData) } self.viewModel.outputs.goToRiskMessagingModal .observeForControllerAction() .observeValues { [weak self] isApplePay in self?.goToRiskMessagingModal(isApplePay: isApplePay) } self.viewModel.outputs.goToThanks .observeForControllerAction() .observeValues { [weak self] data in generateNotificationSuccessFeedback() self?.goToThanks(data: data) } self.viewModel.outputs.notifyDelegateUpdatePledgeDidSucceedWithMessage .observeForUI() .observeValues { [weak self] message in guard let self = self else { return } self.delegate?.pledgeViewControllerDidUpdatePledge(self, message: message) } self.viewModel.outputs.popToRootViewController .observeForControllerAction() .observeValues { [weak self] in self?.navigationController?.popToRootViewController(animated: true) } Keyboard.change .observeForUI() .observeValues { [weak self] change in self?.rootScrollView.handleKeyboardVisibilityDidChange(change) } self.projectTitleLabel.rac.text = self.viewModel.outputs.projectTitle self.projectTitleLabel.rac.hidden = self.viewModel.outputs.projectTitleLabelHidden self.descriptionSectionSeparator.rac.hidden = self.viewModel.outputs.descriptionSectionSeparatorHidden self.summarySectionSeparator.rac.hidden = self.viewModel.outputs.summarySectionSeparatorHidden self.viewModel.outputs.rootStackViewLayoutMargins .observeForUI() .observeValues { [weak self] margins in self?.rootStackView.layoutMargins = margins } self.localPickupLocationView.rac.hidden = self.viewModel.outputs.localPickupViewHidden self.shippingLocationViewController.view.rac.hidden = self.viewModel.outputs.shippingLocationViewHidden self.shippingSummaryView.rac.hidden = self.viewModel.outputs.shippingSummaryViewHidden self.paymentMethodsViewController.view.rac.hidden = self.viewModel.outputs.paymentMethodsViewHidden self.pledgeAmountViewController.view.rac.hidden = self.viewModel.outputs.pledgeAmountViewHidden self.pledgeAmountSummaryViewController.view.rac.hidden = self.viewModel.outputs.pledgeAmountSummaryViewHidden self.pledgeExpandableRewardsHeaderViewController.view.rac.hidden = self.viewModel.outputs.expandableRewardsHeaderViewHidden self.viewModel.outputs.title .observeForUI() .observeValues { [weak self] title in guard let self = self else { return } _ = self |> \.title %~ { _ in title } } self.viewModel.outputs.processingViewIsHidden .observeForUI() .observeValues { [weak self] isHidden in if isHidden { self?.hideProcessingView() } else { self?.showProcessingView() } } self.viewModel.outputs.showWebHelp .observeForControllerAction() .observeValues { [weak self] helpType in guard let self = self else { return } self.paymentSheetAppearanceDelegate?.pledgeViewControllerPaymentSheet(self, hidden: true) self.presentHelpWebViewController(with: helpType, presentationStyle: .formSheet) } // MARK: Errors self.viewModel.outputs.showErrorBannerWithMessage .observeForControllerAction() .observeValues { [weak self] errorMessage in self?.messageBannerViewController?.showBanner(with: .error, message: errorMessage) } self.viewModel.outputs.showApplePayAlert .observeForControllerAction() .observeValues { [weak self] title, message in self?.presentApplePayInvalidAmountAlert(title: title, message: message) } } private func goToPaymentAuthorization(_ paymentAuthorizationData: PaymentAuthorizationData) { let request = PKPaymentRequest .paymentRequest( for: paymentAuthorizationData.project, reward: paymentAuthorizationData.reward, allRewardsTotal: paymentAuthorizationData.allRewardsTotal, additionalPledgeAmount: paymentAuthorizationData.additionalPledgeAmount, allRewardsShippingTotal: paymentAuthorizationData.allRewardsShippingTotal, merchantIdentifier: paymentAuthorizationData.merchantIdentifier ) guard let paymentAuthorizationViewController = PKPaymentAuthorizationViewController(paymentRequest: request) else { return } paymentAuthorizationViewController.delegate = self self.present(paymentAuthorizationViewController, animated: true) } private func goToRiskMessagingModal(isApplePay: Bool) { let viewController = RiskMessagingViewController() viewController.configure(isApplePay: isApplePay) viewController.delegate = self let offset = self.view.bounds.height * Layout.Style.modalHeightMultiplier self.presentViewControllerWithSheetOverlay(viewController, offset: offset) } private func goToThanks(data: ThanksPageData) { let thanksVC = ThanksViewController.configured(with: data) self.navigationController?.pushViewController(thanksVC, animated: true) } private func presentApplePayInvalidAmountAlert(title: String, message: String) { self.present(UIAlertController.alert(title, message: message), animated: true) } // MARK: - Actions @objc private func dismissKeyboard() { self.view.endEditing(true) } // MARK: - Functions private func configureDisclaimerView() { guard let attributedText = attributedLearnMoreText() else { return } self.pledgeDisclaimerView.configure(with: ("icon-not-a-store", attributedText)) } private func goToLoginSignup(with intent: LoginIntent, project: Project, reward: Reward) { let loginSignupViewController = LoginToutViewController.configuredWith( loginIntent: intent, project: project, reward: reward ) let navigationController = UINavigationController(rootViewController: loginSignupViewController) let navigationBarHeight = navigationController.navigationBar.bounds.height if #available(iOS 13.0, *) { self.present(navigationController, animated: true) } else { self.presentViewControllerWithSheetOverlay(navigationController, offset: navigationBarHeight) } } private func beginSCAFlow(withClientSecret secret: String) { let setupIntentConfirmParams = STPSetupIntentConfirmParams(clientSecret: secret) STPPaymentHandler.shared() .confirmSetupIntent(setupIntentConfirmParams, with: self) { [weak self] status, _, error in self?.viewModel.inputs.scaFlowCompleted(with: status, error: error) } } } // MARK: - STPAuthenticationContext extension PledgeViewController: STPAuthenticationContext { func authenticationPresentingViewController() -> UIViewController { return self } } // MARK: - PKPaymentAuthorizationViewControllerDelegate extension PledgeViewController: PKPaymentAuthorizationViewControllerDelegate { func paymentAuthorizationViewController( _: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void ) { let paymentDisplayName = payment.token.paymentMethod.displayName let paymentNetworkName = payment.token.paymentMethod.network?.rawValue let transactionId = payment.token.transactionIdentifier self.viewModel.inputs.paymentAuthorizationDidAuthorizePayment(paymentData: ( paymentDisplayName, paymentNetworkName, transactionId )) STPAPIClient.shared.createToken(with: payment) { [weak self] token, error in guard let self = self else { return } let status = self.viewModel.inputs.stripeTokenCreated(token: token?.tokenId, error: error) let result = PKPaymentAuthorizationResult(status: status, errors: []) completion(result) } } func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) { controller.dismiss(animated: true, completion: { [weak self] in self?.viewModel.inputs.paymentAuthorizationViewControllerDidFinish() }) } } // MARK: - PledgeScreenCTAContainerViewDelegate extension PledgeViewController: PledgeViewCTAContainerViewDelegate { func goToLoginSignup() { self.paymentSheetAppearanceDelegate?.pledgeViewControllerPaymentSheet(self, hidden: true) self.viewModel.inputs.goToLoginSignupTapped() } func applePayButtonTapped() { self.paymentSheetAppearanceDelegate?.pledgeViewControllerPaymentSheet(self, hidden: true) self.viewModel.inputs.applePayButtonTapped() } func submitButtonTapped() { self.paymentSheetAppearanceDelegate?.pledgeViewControllerPaymentSheet(self, hidden: true) self.viewModel.inputs.submitButtonTapped() } func termsOfUseTapped(with helpType: HelpType) { self.paymentSheetAppearanceDelegate?.pledgeViewControllerPaymentSheet(self, hidden: true) self.viewModel.inputs.termsOfUseTapped(with: helpType) } } // MARK: - PledgeAmountViewControllerDelegate extension PledgeViewController: PledgeAmountViewControllerDelegate { func pledgeAmountViewController( _: PledgeAmountViewController, didUpdateWith data: PledgeAmountData ) { self.viewModel.inputs.pledgeAmountViewControllerDidUpdate(with: data) } } // MARK: - PledgeShippingLocationViewControllerDelegate extension PledgeViewController: PledgeShippingLocationViewControllerDelegate { func pledgeShippingLocationViewController( _: PledgeShippingLocationViewController, didSelect shippingRule: ShippingRule ) { self.viewModel.inputs.shippingRuleSelected(shippingRule) } func pledgeShippingLocationViewControllerLayoutDidUpdate(_: PledgeShippingLocationViewController) {} func pledgeShippingLocationViewControllerFailedToLoad(_: PledgeShippingLocationViewController) {} } // MARK: - PledgeViewControllerMessageDisplaying extension PledgeViewController: PledgeViewControllerMessageDisplaying { func pledgeViewController(_: UIViewController, didErrorWith message: String) { self.messageBannerViewController?.showBanner(with: .error, message: message) } func pledgeViewController(_: UIViewController, didSucceedWith message: String) { self.messageBannerViewController?.showBanner(with: .success, message: message) } } // MARK: - PledgePaymentMethodsViewControllerDelegate extension PledgeViewController: PledgePaymentMethodsViewControllerDelegate { func pledgePaymentMethodsViewController( _: PledgePaymentMethodsViewController, didSelectCreditCard paymentSource: PaymentSourceSelected ) { self.viewModel.inputs.creditCardSelected(with: paymentSource) } func pledgePaymentMethodsViewController(_: PledgePaymentMethodsViewController, loading flag: Bool) { if flag { self.showProcessingView() } else { self.hideProcessingView() } } } // MARK: - PledgeDisclaimerViewDelegate extension PledgeViewController: PledgeDisclaimerViewDelegate { func pledgeDisclaimerView(_: PledgeDisclaimerView, didTapURL _: URL) { self.viewModel.inputs.pledgeDisclaimerViewDidTapLearnMore() } } // MARK: - RiskMessagingViewControllerDelegate extension PledgeViewController: RiskMessagingViewControllerDelegate { func riskMessagingViewControllerDismissed(_: RiskMessagingViewController, isApplePay: Bool) { self.viewModel.inputs.riskMessagingViewControllerDismissed(isApplePay: isApplePay) } } // MARK: - Styles private let pledgeDisclaimerViewStyle: ViewStyle = { view in view |> roundedStyle(cornerRadius: Layout.Style.cornerRadius) } private let projectTitleLabelStyle: LabelStyle = { label in label |> \.font .~ UIFont.ksr_body().bolded |> \.numberOfLines .~ 0 } private let rootScrollViewStyle: ScrollStyle = { scrollView in scrollView |> \.showsVerticalScrollIndicator .~ false |> \.alwaysBounceVertical .~ true } private let rootStackViewStyle: StackViewStyle = { stackView in stackView |> \.axis .~ NSLayoutConstraint.Axis.vertical |> \.spacing .~ Styles.grid(4) |> \.isLayoutMarginsRelativeArrangement .~ true } private let rootInsetStackViewStyle: StackViewStyle = { stackView in stackView |> \.axis .~ NSLayoutConstraint.Axis.vertical |> \.spacing .~ Styles.grid(4) |> \.isLayoutMarginsRelativeArrangement .~ true |> \.layoutMargins .~ UIEdgeInsets( topBottom: 0, leftRight: Layout.Margin.leftRight ) } // MARK: - Functions private func attributedLearnMoreText() -> NSAttributedString? { guard let trustLink = HelpType.trust.url( withBaseUrl: AppEnvironment.current.apiService.serverConfig.webBaseUrl )?.absoluteString else { return nil } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 2 let attributedLine1String = Strings.Kickstarter_is_not_a_store() .attributed( with: UIFont.ksr_footnote(), foregroundColor: .ksr_support_400, attributes: [.paragraphStyle: paragraphStyle], bolding: [Strings.Kickstarter_is_not_a_store()] ) let line2String = Strings.Its_a_way_to_bring_creative_projects_to_life_Learn_more_about_accountability( trust_link: trustLink ) guard let attributedLine2String = try? NSMutableAttributedString( data: Data(line2String.utf8), options: [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil ) else { return nil } let attributes: String.Attributes = [ .font: UIFont.ksr_footnote(), .foregroundColor: UIColor.ksr_support_400, .paragraphStyle: paragraphStyle, .underlineStyle: 0 ] let fullRange = (attributedLine2String.string as NSString).range(of: attributedLine2String.string) attributedLine2String.addAttributes(attributes, range: fullRange) let attributedString = attributedLine1String + NSAttributedString(string: "\n") + attributedLine2String return attributedString }
7c282623ddc1b2dee6debcaab646f90c
32.2362
108
0.745278
false
false
false
false
github/Nimble
refs/heads/master
Nimble/Matchers/BeLogical.swift
apache-2.0
1
import Foundation func _beBool(#expectedValue: BooleanType, #stringValue: String, #falseMatchesNil: Bool) -> MatcherFunc<BooleanType> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be \(stringValue)" let actual = actualExpression.evaluate() if expectedValue { return actual?.boolValue == expectedValue.boolValue } else if !falseMatchesNil { return actual != nil && actual!.boolValue != !expectedValue.boolValue } else { return actual?.boolValue != !expectedValue.boolValue } } } // mark: beTrue() / beFalse() public func beTrue() -> MatcherFunc<Bool> { return equal(true).withFailureMessage { failureMessage in failureMessage.postfixMessage = "be true" } } public func beFalse() -> MatcherFunc<Bool> { return equal(false).withFailureMessage { failureMessage in failureMessage.postfixMessage = "be false" } } // mark: beTruthy() / beFalsy() public func beTruthy() -> MatcherFunc<BooleanType> { return _beBool(expectedValue: true, stringValue: "truthy", falseMatchesNil: true) } public func beFalsy() -> MatcherFunc<BooleanType> { return _beBool(expectedValue: false, stringValue: "falsy", falseMatchesNil: true) } extension NMBObjCMatcher { public class func beTruthyMatcher() -> NMBObjCMatcher { return NMBObjCMatcher { actualBlock, failureMessage, location in let block = ({ (actualBlock() as? NSNumber)?.boolValue ?? false as BooleanType? }) let expr = Expression(expression: block, location: location) return beTruthy().matches(expr, failureMessage: failureMessage) } } public class func beFalsyMatcher() -> NMBObjCMatcher { return NMBObjCMatcher { actualBlock, failureMessage, location in let block = ({ (actualBlock() as? NSNumber)?.boolValue ?? false as BooleanType? }) let expr = Expression(expression: block, location: location) return beFalsy().matches(expr, failureMessage: failureMessage) } } public class func beTrueMatcher() -> NMBObjCMatcher { return NMBObjCMatcher { actualBlock, failureMessage, location in let block = ({ (actualBlock() as? NSNumber)?.boolValue as Bool? }) let expr = Expression(expression: block, location: location) return beTrue().matches(expr, failureMessage: failureMessage) } } public class func beFalseMatcher() -> NMBObjCMatcher { return NMBObjCMatcher { actualBlock, failureMessage, location in let block = ({ (actualBlock() as? NSNumber)?.boolValue as Bool? }) let expr = Expression(expression: block, location: location) return beFalse().matches(expr, failureMessage: failureMessage) } } }
80d743314b5ade85dbbf07f60de8094a
38.205479
117
0.663871
false
false
false
false
urdnot-ios/ShepardAppearanceConverter
refs/heads/master
ShepardAppearanceConverter/ShepardAppearanceConverter/Library/IBStyles/IBStyles.swift
mit
1
// // IBStyles.swift // // Created by Emily Ivie on 2/24/15. // import UIKit // MARK: Stylesheet Base and Example public protocol Stylesheet { static var fontsList: [IBFontStyle: String] { get } static var stylesList: [String: IBStyleProperties] { get } static func applyGlobalStyles(window: UIWindow?) } extension Stylesheet { public static var fontsList: [IBFontStyle: String] { return [:] } public static var stylesList: [String: IBStyleProperties] { return [:] } public static func applyGlobalStyles(window: UIWindow?) {} } /// extend this struct in your own styles file to add your styles to the IBStyles functionality public struct Styles: Stylesheet {} //Example: // //extension Styles { // public static var fontsList: [IBFontStyle: String] { // return [ // .Normal: "Avenir-Regular", // ] // } // // public static var stylesList: [String: IBStyleProperties] { // return [ // "NormalColorText.17": [ // .Font: IBFont.SizeStyle(17,.Normal), // .TextColor: Colors.NormalColor, // ], // ] // } // // public static func applyGlobalStyles(window: UIWindow?) { // IBStyles.fontsList = fontsList // IBStyles.stylesList = stylesList // } //} //MARK: IBStylePropertyName /** All the current possible IBStyle options. Note: neither StateX or IPad|IPhoneStyles are properly visible in Interface Builder. Use the @IBInspectable properties in IBStyledButton and IBStyledRootView to set them. - Inherit: expects a string of IBStyle names. Applies them in order listed, with current styles taking precedence. - IPadStyles: an IBStyleProperties list of styles to only apply when on an iPad device. - IPhoneStyles: an IBStyleProperties list of styles to only apply when on an iPhone device. - Font: add new fonts to IBFont enum. This field will only accept IBFont enum values. - TextColor: UIColor - CornerRadius: Double - BorderWidth: Double - BorderColor: UIColor - BackgroundColor: UIColor - BackgroundGradient: see IBGradient. Example: IBGradient(direction:.Vertical, colors:[UIColor.redColor(),UIColor.blackColor()]) - StateActive: an IBStyleProperties list of styles to only apply when button is active. - StatePressed: an IBStyleProperties list of styles to only apply when button is pressed. - StateDisabled: an IBStyleProperties list of styles to only apply when button is disabled. - StateSelected: an IBStyleProperties list of styles to only apply when button is selected. Dunno when that is. */ public enum IBStylePropertyName { case Inherit //[String] case Font //IBFont case TextColor //UIColor case CornerRadius //Double case BorderWidth //Double case BorderColor //UIColor case BackgroundColor //UIColor case BackgroundGradient //IBGradient case StateActive //IBStyleProperties case StatePressed //IBStyleProperties case StateDisabled //IBStyleProperties case StateSelected //IBStyleProperties } public typealias IBStyleProperties = [IBStylePropertyName: Any] public typealias IBStyleGroup = [String: IBStyleProperties] //MARK: IBStyles /** The base functionality for applying IBStyles to an IBStylable element. Stores all styles in a static/shared struct. */ public struct IBStyles { // I can't figure out any way to let Styles write to IBStyles at IB app load since appDelegate is never called in IB :( // So, this kinda sucks: public static var stylesList: [String: IBStyleProperties] = Styles.stylesList public static var fontsList: [IBFontStyle: String] = Styles.fontsList // http://iosfonts.com/ public static var deviceKind = UIDevice.currentDevice().userInterfaceIdiom ?? UIUserInterfaceIdiom.Phone public static var hasAppliedGlobalStyles = false /** Verify that all styles are the expected type. */ private static func validate(properties: IBStyleProperties) { for (type,value) in properties{ switch (type){ case .Inherit: assert(value as? [String] != nil) case .Font: assert(value as? IBFont != nil) case .TextColor: assert(value as? UIColor != nil) case .CornerRadius: assert(value as? Double != nil) case .BorderWidth: assert(value as? Double != nil) case .BorderColor: fallthrough case .BackgroundColor: assert(value as? UIColor != nil) case .BackgroundGradient: assert(value as? IBGradient != nil) //what if I add other gradients? case .StateActive: fallthrough case .StatePressed: fallthrough case .StateDisabled: fallthrough case .StateSelected: assert(value as? IBStyleProperties != nil) validate(value as! IBStyleProperties) } } } /** Assembles a list of styles for this element, in order of priority (inherit, main, device). :param: identifier the key of the element :param: to (element) the element to be styled */ public static func apply(identifier: String, to element: UIView!) { if element.isInterfaceBuilder && !hasAppliedGlobalStyles { Styles.applyGlobalStyles(element?.window) hasAppliedGlobalStyles = true } if let properties = stylesList[identifier] { let inheritProperties = properties[.Inherit] as? [String] ?? [] var properties2 = IBStyleProperties() for name in inheritProperties { if let styles = stylesList[name] { properties2 = properties2.merge(styles) } } properties2 = properties2.merge(properties) applyProperties(properties2, to: element) } } /** A special-case version of apply() that only applies state-specific styles. This allows for only changing specific styles rather than rewriting everything. :param: identifier the key of the element :param: to (element) the element to be styled :param: forState the UIControlState in play: Normal, Disabled, Highlighted, or Selected */ public static func apply(identifier: String, to element: UIView!, forState state: UIControlState) { var properties = stylesList[identifier] ?? [:] switch (state) { case UIControlState.Normal : if let p2 = properties[.StateActive] as? IBStyleProperties { properties = p2 } case UIControlState.Disabled : if let p2 = properties[.StateDisabled] as? IBStyleProperties { properties = p2 } case UIControlState.Highlighted : if let p2 = properties[.StatePressed] as? IBStyleProperties { properties = p2 } case UIControlState.Selected : if let p2 = properties[.StateSelected] as? IBStyleProperties { properties = p2 } default: return //don't do anything } applyProperties(properties, to: element, forState: state) } /** Applies a list of styles to an element :param: properties the list of styles :param: to (element) the element to be styled :param: forState (Optional) the UIControlState in play - defaults to normal */ private static func applyProperties(properties: IBStyleProperties, to element: UIView!, forState state: UIControlState = .Normal) { guard element != nil else { return } for (type, value) in properties { // let elementState: UIControlState? //for later switch (type){ case .Font: if let fontClass = value as? IBFont { if let font = fontClass.getUIFont() { if let label = element as? UILabel { label.font = font } if let button = element as? UIButton { button.titleLabel?.font = font } if let textfield = element as? UITextField { textfield.font = font } if let textview = element as? UITextView { textview.font = font } } } case .TextColor: if let color = value as? UIColor { if let label = element as? UILabel { label.textColor = color } if let button = element as? UIButton { button.setTitleColor(color, forState: state) } if let textfield = element as? UITextField { textfield.textColor = color } if let textview = element as? UITextView { textview.textColor = color } } case .CornerRadius: element.layer.cornerRadius = CGFloat(value as? Double ?? 0.0) element.layer.masksToBounds = element.layer.cornerRadius > CGFloat(0) case .BorderWidth: element.layer.borderWidth = CGFloat(value as? Double ?? 0.0) case .BorderColor: if let color = value as? UIColor { element.layer.borderColor = (color).CGColor } case .BackgroundColor: if let color = value as? UIColor { element.layer.backgroundColor = color.CGColor } case .BackgroundGradient: if let gradient = value as? IBGradient { let gradientView = gradient.createGradientView(element.bounds) element.insertSubview(gradientView, atIndex: 0) gradientView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] } // And now, state-specific styles: /* // currently disabled, because not all styles can be set forState, so have to change dynamically on events // see IBStyledButton for more case .StateActive: if let p2 = value as? IBStyleProperties { applyProperties(p2, to: element, forState: .Normal) } case .StatePressed: if let p2 = value as? IBStyleProperties { applyProperties(p2, to: element, forState: .Highlighted) } case .StateDisabled: if let p2 = value as? IBStyleProperties { applyProperties(p2, to: element, forState: .Disabled) } case .StateSelected: if let p2 = value as? IBStyleProperties { applyProperties(p2, to: element, forState: .Selected) } */ default: break //skip the rest } } } } //MARK: IBFont public enum IBFontStyle: String { case Normal, Italic, Medium, SemiBold, Bold } public enum IBFont { case SizeStyle(Int,IBFontStyle) public func getUIFont() -> UIFont? { switch(self) { case .SizeStyle(let size, let style): let name = IBStyles.fontsList[style] let cgSize = CGFloat(size) switch style { case .Normal: return name != nil ? UIFont(name: name!, size: cgSize) : UIFont.systemFontOfSize(cgSize) case .Italic: return name != nil ? UIFont(name: name!, size: cgSize) : UIFont.italicSystemFontOfSize(cgSize) case .Medium: return name != nil ? UIFont(name: name!, size: cgSize) : UIFont.systemFontOfSize(cgSize) case .SemiBold: return name != nil ? UIFont(name: name!, size: cgSize) : UIFont.boldSystemFontOfSize(cgSize) case .Bold: return name != nil ? UIFont(name: name!, size: cgSize) : UIFont.boldSystemFontOfSize(cgSize) } } } } //MARK: IBGradient /** Just a helpful way to define background gradients. See CAGradientLayer for more information on the properties used here. - direction: .Vertical or .Horizontal - colors - locations - createGradientView() */ public struct IBGradient { /** Quick enum to more clearly define IBGradient direction (Vertical or Horizontal). */ public enum Direction { case Vertical,Horizontal } public var direction: Direction = .Vertical public var colors: [UIColor] = [] public var locations: [Double] = [] init(direction: Direction, colors: [UIColor]) { self.direction = direction self.colors = colors } /** Generates a IBGradientView from the gradient values provided. :param: bounds The size to use in creating the gradient view. :returns: a UIView with a gradient background layer */ public func createGradientView(bounds: CGRect) -> (IBGradientView) { let gradientView = IBGradientView(frame: bounds) gradientView.setLayerColors(colors) if !locations.isEmpty { gradientView.setLayerLocations(locations) } else { gradientView.setLayerEndPoint(direction == .Vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)) } return gradientView } } //MARK: IBGradientView /** Allows for an auto-resizable CAGradientLayer (like, say, during device orientation changes). IBStyles IBStylePropertyName.BackgroundGradient uses this. */ public class IBGradientView: UIView { /** Built-in UIView function that responds to .layer requests. Changes the .layer property of the view to be CAGradientLayer. But we still have to change all interactions with .layer to recognize this new type, hence the other functions. :returns: CAGradientLayer .layer reference */ override public class func layerClass() -> (AnyClass) { return CAGradientLayer.self } /** Sets the colors of the gradient. Can be more than two. :param: colors a list of UIColor elements. */ public func setLayerColors(colors: [UIColor]) { let layer = self.layer as! CAGradientLayer layer.colors = colors.map({ $0.CGColor }) } /** Sets the locations of the gradient. See CAGradientLayer documentation for how this work, because I only used endPoint myself. :param: locations a list of Double location positions. */ public func setLayerLocations(locations: [Double]) { let layer = self.layer as! CAGradientLayer layer.locations = locations.map({ NSNumber(double: $0) }) } /** Sets the start point of the gradient (this is the simplest way to define a gradient: setting the start or end point) :param: startPoint a CGPoint using 0.0 - 1.0 values */ public func setLayerStartPoint(startPoint: CGPoint) { let layer = self.layer as! CAGradientLayer layer.startPoint = startPoint } /** Sets the end point of the gradient (this is the simplest way to define a gradient: setting the start or end point) :param: endPoint a CGPoint using 0.0 - 1.0 values */ public func setLayerEndPoint(endPoint: CGPoint) { let layer = self.layer as! CAGradientLayer layer.endPoint = endPoint } }
2e5d4ae80d5d1755f20282bf2f7e8e38
38.707022
182
0.582475
false
false
false
false
Moliholy/devslopes-smack-animation
refs/heads/master
Smack/Controller/CreateAccountVC.swift
bsd-2-clause
1
// // CreateAccountVC.swift // Smack // // Created by Jonny B on 7/14/17. // Copyright © 2017 Jonny B. All rights reserved. // import UIKit class CreateAccountVC: UIViewController { // Outlets @IBOutlet weak var usernameTxt: UITextField! @IBOutlet weak var emailTxt: UITextField! @IBOutlet weak var passTxt: UITextField! @IBOutlet weak var userImg: UIImageView! @IBOutlet weak var spinner: UIActivityIndicatorView! // Variables var avatarName = "profileDefault" var avatarColor = "[0.5, 0.5, 0.5, 1]" var bgColor : UIColor? override func viewDidLoad() { super.viewDidLoad() setupView() } override func viewDidAppear(_ animated: Bool) { if UserDataService.instance.avatarName != "" { userImg.image = UIImage(named: UserDataService.instance.avatarName) avatarName = UserDataService.instance.avatarName if avatarName.contains("light") && bgColor == nil { userImg.backgroundColor = UIColor.lightGray } } } @IBAction func createAccntPressed(_ sender: Any) { spinner.isHidden = false spinner.startAnimating() guard let name = usernameTxt.text , usernameTxt.text != "" else { return } guard let email = emailTxt.text , emailTxt.text != "" else { return } guard let pass = passTxt.text , passTxt.text != "" else { return } AuthService.instance.registerUser(email: email, password: pass) { (success) in if success { AuthService.instance.loginUser(email: email, password: pass, completion: { (success) in if success { AuthService.instance.createUser(name: name, email: email, avatarName: self.avatarName, avatarColor: self.avatarColor, completion: { (success) in if success { self.spinner.isHidden = true self.spinner.stopAnimating() self.performSegue(withIdentifier: UNWIND, sender: nil) NotificationCenter.default.post(name: NOTIF_USER_DATA_DID_CHANGE, object: nil) } }) } }) } } } @IBAction func pickAvatarPressed(_ sender: Any) { performSegue(withIdentifier: TO_AVATAR_PICKER, sender: nil) } @IBAction func pickBGColorPressed(_ sender: Any) { let r = CGFloat(arc4random_uniform(255)) / 255 let g = CGFloat(arc4random_uniform(255)) / 255 let b = CGFloat(arc4random_uniform(255)) / 255 bgColor = UIColor(red: r, green: g, blue: b, alpha: 1) avatarColor = "[\(r), \(g), \(b), 1]" UIView.animate(withDuration: 0.2) { self.userImg.backgroundColor = self.bgColor } } @IBAction func closePressed(_ sender: Any) { performSegue(withIdentifier: UNWIND, sender: nil) } func setupView() { spinner.isHidden = true usernameTxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder]) emailTxt.attributedPlaceholder = NSAttributedString(string: "email", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder]) passTxt.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder]) let tap = UITapGestureRecognizer(target: self, action: #selector(CreateAccountVC.handleTap)) view.addGestureRecognizer(tap) } @objc func handleTap() { view.endEditing(true) } }
667afdf7ad31d7da303b6960b1b09c3f
37.019802
168
0.601823
false
false
false
false
sarvex/SwiftRecepies
refs/heads/master
Health/Setting up Your App for HealthKit/Setting up Your App for HealthKit/ViewController.swift
isc
1
// // ViewController.swift // Setting up Your App for HealthKit // // Created by vandad on 227//14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import HealthKit class ViewController: UIViewController { let heightQuantity = HKQuantityType.quantityTypeForIdentifier( HKQuantityTypeIdentifierHeight) let weightQuantity = HKQuantityType.quantityTypeForIdentifier( HKQuantityTypeIdentifierBodyMass) let heartRateQuantity = HKQuantityType.quantityTypeForIdentifier( HKQuantityTypeIdentifierHeartRate) lazy var healthStore = HKHealthStore() /* The type of data that we wouldn't write into the health store */ lazy var typesToShare: Set<NSObject> = { return Set([self.heightQuantity, self.weightQuantity]) }() /* We want to read this type of data */ lazy var typesToRead: Set<NSObject> = { return Set([self.heightQuantity, self.weightQuantity, self.heartRateQuantity]) }() /* Ask for permission to access the health store */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if HKHealthStore.isHealthDataAvailable(){ healthStore.requestAuthorizationToShareTypes(typesToShare, readTypes: typesToRead, completion: {(succeeded: Bool, error: NSError!) in if succeeded && error == nil{ println("Successfully received authorization") } else { if let theError = error{ println("Error occurred = \(theError)") } } }) } else { println("Health data is not available") } } }
18c7aba56282ef1aaeae1b6552837e32
29.55
83
0.686579
false
false
false
false
haawa799/WaniKani-iOS
refs/heads/master
Pods/WaniKit/Sources/WaniKit/KanjiInfo.swift
gpl-3.0
2
// // KanjiInfo.swift // Pods // // Created by Andriy K. on 12/27/15. // // import Foundation public struct UserSpecific: DictionaryInitialization { // Dictionary keys private static let keySrs = "srs" private static let keySrsNumeric = "srs_numeric" private static let keyUnlockDate = "unlocked_date" private static let keyAvaliableDate = "available_date" private static let keyBurned = "burned" private static let keyBurnedDate = "burned_date" private static let keyMeaningCorrect = "meaning_correct" private static let keyMeaningIncorrect = "meaning_incorrect" private static let keyMeaningMaxStreak = "meaning_max_streak" private static let keyMeaningCurrentStreak = "meaning_current_streak" private static let keyReadingCorrect = "reading_correct" private static let keyReadingIncorrect = "reading_incorrect" private static let keyReadingMaxStreak = "reading_max_streak" private static let keyReadingCurrentStreak = "reading_current_streak" private static let keyMeaningNote = "meaning_note" private static let keyUserSynonyms = "user_synonyms" private static let keyReadingNote = "reading_note" // Fields public var srs: String? public var srsNumeric: Int? public var unlockedDate: NSDate? public var availableDate: NSDate? public var burned: Bool public var burnedDate: NSDate? public var meaningCorrect: Int? public var meaningIncorrect: Int? public var meaningMaxStreak: Int? public var meaningCurrentStreak: Int? public var readingCorrect: Int? public var readingIncorrect: Int? public var readingMaxStreak: Int? public var readingCurrentStreak: Int? public var meaningNote: String? public var userSynonyms: String? public var readingNote: String? public init(dict: NSDictionary) { srs = (dict[UserSpecific.keySrs] as? String) srsNumeric = (dict[UserSpecific.keySrsNumeric] as? Int) burned = (dict[UserSpecific.keyBurned] as! Bool) if let unlock = dict[UserSpecific.keyUnlockDate] as? Int { unlockedDate = NSDate(timeIntervalSince1970: NSTimeInterval(unlock)) } if let avaliable = dict[UserSpecific.keyAvaliableDate] as? Int { availableDate = NSDate(timeIntervalSince1970: NSTimeInterval(avaliable)) } if let burnedDateInt = dict[UserSpecific.keyAvaliableDate] as? Int { burnedDate = NSDate(timeIntervalSince1970: NSTimeInterval(burnedDateInt)) } meaningCorrect = (dict[UserSpecific.keyMeaningCorrect] as? Int) meaningIncorrect = (dict[UserSpecific.keyMeaningIncorrect] as? Int) meaningMaxStreak = (dict[UserSpecific.keyMeaningMaxStreak] as? Int) meaningCurrentStreak = (dict[UserSpecific.keyMeaningCurrentStreak] as? Int) readingCorrect = (dict[UserSpecific.keyReadingCorrect] as? Int) readingIncorrect = (dict[UserSpecific.keyReadingIncorrect] as? Int) readingMaxStreak = (dict[UserSpecific.keyReadingMaxStreak] as? Int) readingCurrentStreak = (dict[UserSpecific.keyReadingCurrentStreak] as? Int) meaningNote = (dict[UserSpecific.keyMeaningNote] as? String) userSynonyms = (dict[UserSpecific.keyUserSynonyms] as? String) readingNote = (dict[UserSpecific.keyReadingNote] as? String) } } public struct KanjiInfo { // Dictionary keys private static let keyCharacter = "character" private static let keyMeaning = "meaning" private static let keyOnyomi = "onyomi" private static let keyKunyomi = "kunyomi" private static let keyNanori = "nanori" private static let keyImportantReading = "important_reading" private static let keyLevel = "level" private static let keyUserSpecific = "user_specific" public var character: String public var meaning: String? public var onyomi: String? public var kunyomi: String? public var nanori: String? public var importantReading: String? public var level: Int public var userSpecific: UserSpecific? } extension KanjiInfo: DictionaryInitialization { public init(dict: NSDictionary) { character = dict[KanjiInfo.keyCharacter] as! String meaning = dict[KanjiInfo.keyMeaning] as? String onyomi = dict[KanjiInfo.keyOnyomi] as? String kunyomi = dict[KanjiInfo.keyKunyomi] as? String nanori = dict[KanjiInfo.keyNanori] as? String importantReading = dict[KanjiInfo.keyImportantReading] as? String level = dict[KanjiInfo.keyLevel] as! Int if let userSpecificDict = dict[KanjiInfo.keyUserSpecific] as? NSDictionary { userSpecific = UserSpecific(dict: userSpecificDict) } } }
c59f11e76df42b912743c30a5df71e14
35.764228
80
0.747843
false
false
false
false
BrunoMazzo/CocoaHeadsApp
refs/heads/master
CocoaHeadsApp/Classes/Events/Views/EventsListView.swift
mit
3
import UIKit import RxSwift class EventListView: NibDesignable { let viewModel = EventsListViewModel() var dataSource :EventsListTableDataSource! var delegate :EventsListTableDelegate! let disposeBag = DisposeBag() @IBOutlet weak var listEventsTableView :UITableView! override func viewDidLoad() { super.viewDidLoad() self.listEventsTableView.registerNib(R.nib.eventsListTableViewCell) self.dataSource = EventsListTableDataSource(viewModel: self.viewModel) self.delegate = EventsListTableDelegate(viewModel: self.viewModel) self.listEventsTableView.dataSource = self.dataSource self.listEventsTableView.delegate = self.delegate viewModel.items.asObservable().subscribeNext { [weak self] (items) in self?.listEventsTableView.reloadData() }.addDisposableTo(self.disposeBag) //viewModel.loadMoreItens() } }
527e23158e09031c2da0e7576aac2414
34.884615
78
0.720257
false
false
false
false
PedroTrujilloV/TIY-Assignments
refs/heads/master
11--Raiders-of-the-Lost-App/CustomCells/CustomCells/ListTableViewController.swift
cc0-1.0
1
// // ListTableViewController.swift // CustomCells // // Created by Ben Gohlke on 10/19/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class ListTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row % 2 == 0 { return 44.0 } else { return 88.0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row % 2 == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("ExampleCell", forIndexPath: indexPath) as! ExampleCell cell.leftLabel.text = "\(indexPath.row)" cell.rightLabel.text = "The Iron Yard" return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("AnotherCell", forIndexPath: indexPath) as! AnotherCell cell.aLabel.text = "is awesome!" return cell } } }
265341f00862f693fa7dffbcbf7dd25a
23.910448
122
0.609347
false
false
false
false
rb-de0/Fluxer
refs/heads/master
FluxerTests/Dispatcher/DispatcherTests.swift
mit
1
// // DispatcherTests.swift // Fluxer // // Created by rb_de0 on 2017/03/21. // Copyright © 2017年 rb_de0. All rights reserved. // import XCTest @testable import Fluxer class DispatcherTests: XCTestCase { class TestStore: Store { var value = 0 required init(with dispatcher: Dispatcher) {} } class TestAction: Action {} class Test2Action: Action {} class TestAsyncAction: AsyncAction { let expect: XCTestExpectation init(_ expect: XCTestExpectation) { self.expect = expect } func exec(callback: @escaping Dispatcher.AsyncActionCallback) { callback(TestAction()) expect.fulfill() } } func testHandlerCallOrder() { let dispatcher = Dispatcher() var orderList = [Int]() _ = dispatcher.register { _ in orderList.append(0) } _ = dispatcher.register { _ in orderList.append(1) } dispatcher.dispatch(TestAction()) XCTAssertEqual(orderList, [0, 1]) } func testWaitFor() { let dispatcher = Dispatcher() var orderList = [Int]() var waitTokens = [String]() _ = dispatcher.register { action in dispatcher.waitFor(waitTokens, action: action) orderList.append(0) } let token = dispatcher.register { _ in orderList.append(1) } waitTokens.append(token) _ = dispatcher.register { _ in orderList.append(2) } dispatcher.dispatch(TestAction()) XCTAssertEqual(orderList, [1, 0, 2]) } func testStoreSubscribe() { let dispatcher = Dispatcher() let store = TestStore(with: dispatcher) _ = dispatcher.register { action in store.value = 10 } dispatcher.dispatch(TestAction()) XCTAssertEqual(store.value, 10) } func testActionHandler() { let dispatcher = Dispatcher() let store = TestStore(with: dispatcher) _ = dispatcher.register { action in switch action { case _ as TestAction: store.value = 10 case _ as Test2Action: store.value = -1 default: break } } dispatcher.dispatch(TestAction()) XCTAssertEqual(store.value, 10) dispatcher.dispatch(Test2Action()) XCTAssertEqual(store.value, -1) } func testAsyncActionCreator() { let expectation = self.expectation(description: #function) let dispatcher = Dispatcher() let store = TestStore(with: dispatcher) _ = dispatcher.register { _ in store.value = 10 } dispatcher.dispatch { callback in callback(TestAction()) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(store.value, 10) } func testAsyncStoreUpdate() { let expectation = self.expectation(description: #function) let dispatcher = Dispatcher() let store = TestStore(with: dispatcher) _ = dispatcher.register { action in switch action { case _ as TestAction: store.value = 10 case _ as Test2Action: store.value = -1 default: break } } dispatcher.dispatch { callback in XCTAssertEqual(store.value, 0) DispatchQueue.global().async { sleep(2) XCTAssertEqual(store.value, -1) callback(TestAction()) expectation.fulfill() } } dispatcher.dispatch(Test2Action()) waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(store.value, 10) } func testAsyncAction() { let expectation = self.expectation(description: #function) let dispatcher = Dispatcher() let store = TestStore(with: dispatcher) _ = dispatcher.register { _ in store.value = 10 } dispatcher.dispatch(TestAsyncAction(expectation)) waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(store.value, 10) } func testUnregister() { let dispatcher = Dispatcher() let store = TestStore(with: dispatcher) let token = dispatcher.register { action in switch action { case _ as TestAction: store.value = 10 case _ as Test2Action: store.value = -1 default: break } } dispatcher.dispatch(TestAction()) XCTAssertEqual(store.value, 10) dispatcher.unregister(registrationToken: token) dispatcher.dispatch(Test2Action()) XCTAssertEqual(store.value, 10) } }
f272ea17737d2a0500c502c343bd3ef8
23.102564
71
0.486879
false
true
false
false
maicki/plank
refs/heads/master
Sources/Core/ObjectiveCInitExtension.swift
apache-2.0
1
// // ObjectiveCInitExtension.swift // plank // // Created by Rahul Malik on 2/14/17. // // import Foundation let dateValueTransformerKey = "kPlankDateValueTransformerKey" extension ObjCFileRenderer { func renderPostInitNotification(type: String) -> String { return "[[NSNotificationCenter defaultCenter] postNotificationName:kPlankDidInitializeNotification object:self userInfo:@{ kPlankInitTypeKey : @(\(type)) }];" } } extension ObjCModelRenderer { func renderModelObjectWithDictionary() -> ObjCIR.Method { return ObjCIR.method("+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dictionary") { ["return [[self alloc] initWithModelDictionary:dictionary];"] } } func renderDesignatedInit() -> ObjCIR.Method { return ObjCIR.method("- (instancetype)init") { [ "return [self initWithModelDictionary:@{}];" ] } } func renderInitWithBuilder() -> ObjCIR.Method { return ObjCIR.method("- (instancetype)initWithBuilder:(\(builderClassName) *)builder") { [ "NSParameterAssert(builder);", "return [self initWithBuilder:builder initType:PlankModelInitTypeDefault];" ] } } func renderInitWithBuilderWithInitType() -> ObjCIR.Method { return ObjCIR.method("- (instancetype)initWithBuilder:(\(builderClassName) *)builder initType:(PlankModelInitType)initType") { [ "NSParameterAssert(builder);", self.isBaseClass ? ObjCIR.ifStmt("!(self = [super init])") { ["return self;"] } : ObjCIR.ifStmt("!(self = [super initWithBuilder:builder initType:initType])") { ["return self;"] }, self.properties.map { (name, _) in "_\(name.snakeCaseToPropertyName()) = builder.\(name.snakeCaseToPropertyName());" }.joined(separator: "\n"), "_\(self.dirtyPropertiesIVarName) = builder.\(self.dirtyPropertiesIVarName);", ObjCIR.ifStmt("[self class] == [\(self.className) class]") { [renderPostInitNotification(type: "initType")] }, "return self;" ] } } public func renderInitWithModelDictionary() -> ObjCIR.Method { func renderPropertyInit( _ propertyToAssign: String, _ rawObjectName: String, schema: Schema, firstName: String, // TODO: HACK to get enums to work (not clean) counter: Int = 0 ) -> [String] { switch schema { case .array(itemType: .some(let itemType)): let currentResult = "result\(counter)" let currentTmp = "tmp\(counter)" let currentObj = "obj\(counter)" if itemType.isObjCPrimitiveType { return [ "\(propertyToAssign) = \(rawObjectName);" ] } let propertyInit = renderPropertyInit(currentTmp, currentObj, schema: itemType, firstName: firstName, counter: counter + 1).joined(separator: "\n") return [ "NSArray *items = \(rawObjectName);", "NSMutableArray *\(currentResult) = [NSMutableArray arrayWithCapacity:items.count];", ObjCIR.forStmt("id \(currentObj) in items") { [ ObjCIR.ifStmt("\(currentObj) != (id)kCFNull") { [ "id \(currentTmp) = nil;", propertyInit, ObjCIR.ifStmt("\(currentTmp) != nil") {[ "[\(currentResult) addObject:\(currentTmp)];" ]} ]} ]}, "\(propertyToAssign) = \(currentResult);" ] case .set(itemType: .some(let itemType)): let currentResult = "result\(counter)" let currentTmp = "tmp\(counter)" let currentObj = "obj\(counter)" if itemType.isObjCPrimitiveType { return [ "NSArray *items = \(rawObjectName);", "\(propertyToAssign) = [NSSet setWithArray:items];" ] } let propertyInit = renderPropertyInit(currentTmp, currentObj, schema: itemType, firstName: firstName, counter: counter + 1).joined(separator: "\n") return [ "NSArray *items = \(rawObjectName);", "NSMutableSet *\(currentResult) = [NSMutableSet setWithCapacity:items.count];", ObjCIR.forStmt("id \(currentObj) in items") { [ ObjCIR.ifStmt("\(currentObj) != (id)kCFNull") { [ "id \(currentTmp) = nil;", propertyInit, ObjCIR.ifStmt("\(currentTmp) != nil") {[ "[\(currentResult) addObject:\(currentTmp)];" ]} ]} ]}, "\(propertyToAssign) = \(currentResult);" ] case .map(valueType: .some(let valueType)) where valueType.isObjCPrimitiveType == false: let currentResult = "result\(counter)" let currentItems = "items\(counter)" let (currentKey, currentObj, currentStop) = ("key\(counter)", "obj\(counter)", "stop\(counter)") return [ "NSDictionary *\(currentItems) = \(rawObjectName);", "NSMutableDictionary *\(currentResult) = [NSMutableDictionary dictionaryWithCapacity:\(currentItems).count];", ObjCIR.stmt( ObjCIR.msg(currentItems, ("enumerateKeysAndObjectsUsingBlock", ObjCIR.block(["NSString * _Nonnull \(currentKey)", "id _Nonnull \(currentObj)", "__unused BOOL * _Nonnull \(currentStop)"]) { [ ObjCIR.ifStmt("\(currentObj) != nil && \(currentObj) != (id)kCFNull") { renderPropertyInit("\(currentResult)[\(currentKey)]", currentObj, schema: valueType, firstName: firstName, counter: counter + 1) } ] }) ) ), "\(propertyToAssign) = \(currentResult);" ] case .float: return ["\(propertyToAssign) = [\(rawObjectName) doubleValue];"] case .integer: return ["\(propertyToAssign) = [\(rawObjectName) integerValue];"] case .boolean: return ["\(propertyToAssign) = [\(rawObjectName) boolValue];"] case .string(format: .some(.uri)): return ["\(propertyToAssign) = [NSURL URLWithString:\(rawObjectName)];"] case .string(format: .some(.dateTime)): return ["\(propertyToAssign) = [[NSValueTransformer valueTransformerForName:\(dateValueTransformerKey)] transformedValue:\(rawObjectName)];"] case .reference(with: let ref): return ref.force().map { renderPropertyInit(propertyToAssign, rawObjectName, schema: $0, firstName: firstName, counter: counter) } ?? { assert(false, "TODO: Forward optional across methods") return [] }() case .enumT(.integer(let variants)): return renderPropertyInit(propertyToAssign, rawObjectName, schema: .integer, firstName: firstName, counter: counter) case .enumT(.string(let variants)): return ["\(propertyToAssign) = \(enumFromStringMethodName(propertyName: firstName, className: className))(value);"] case .object(let objectRoot): return ["\(propertyToAssign) = [\(objectRoot.className(with: self.params)) modelObjectWithDictionary:\(rawObjectName)];"] case .oneOf(types: let schemas): // TODO Update to create ADT objects let adtClassName = self.typeFromSchema(firstName, schema.nonnullProperty()).trimmingCharacters(in: CharacterSet(charactersIn: "*")) func loop(schema: Schema) -> String { func transformToADTInit(_ lines: [String]) -> [String] { if let assignmentLine = lines.last { let propAssignmentPrefix = "\(propertyToAssign) = " if assignmentLine.hasPrefix(propAssignmentPrefix) { let startIndex = propAssignmentPrefix.endIndex let propertyInitStatement = String(assignmentLine[startIndex...]).trimmingCharacters(in: CharacterSet(charactersIn: " ;")) let adtInitStatement = propAssignmentPrefix + "[\(adtClassName) objectWith\(ObjCADTRenderer.objectName(schema)):\(propertyInitStatement)];" return lines.dropLast() + [adtInitStatement] } } return lines } switch schema { case .object(let objectRoot): return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSDictionary class]] && [\(rawObjectName)[\("type".objcLiteral())] isEqualToString:\(objectRoot.typeIdentifier.objcLiteral())]") { transformToADTInit(["\(propertyToAssign) = [\(objectRoot.className(with: self.params)) modelObjectWithDictionary:\(rawObjectName)];"]) } case .reference(with: let ref): return ref.force().map(loop) ?? { assert(false, "TODO: Forward optional across methods") return "" }() case .float: let encodingConditions = [ "strcmp([\(rawObjectName) objCType], @encode(float)) == 0", "strcmp([\(rawObjectName) objCType], @encode(double)) == 0" ] return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSNumber class]] && (\(encodingConditions.joined(separator: " ||\n")))") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: .float, firstName: firstName, counter: counter)) } case .integer, .enumT(.integer): let encodingConditions = [ "strcmp([\(rawObjectName) objCType], @encode(int)) == 0", "strcmp([\(rawObjectName) objCType], @encode(unsigned int)) == 0", "strcmp([\(rawObjectName) objCType], @encode(short)) == 0", "strcmp([\(rawObjectName) objCType], @encode(unsigned short)) == 0", "strcmp([\(rawObjectName) objCType], @encode(long)) == 0", "strcmp([\(rawObjectName) objCType], @encode(long long)) == 0", "strcmp([\(rawObjectName) objCType], @encode(unsigned long)) == 0", "strcmp([\(rawObjectName) objCType], @encode(unsigned long long)) == 0" ] return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSNumber class]] && (\(encodingConditions.joined(separator: " ||\n")))") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: schema, firstName: firstName, counter: counter)) } case .boolean: return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSNumber class]] && strcmp([\(rawObjectName) objCType], @encode(BOOL)) == 0") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: schema, firstName: firstName, counter: counter)) } case .array(itemType: _): return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSArray class]]") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: schema, firstName: firstName, counter: counter)) } case .set(itemType: _): return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSSet class]]") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: schema, firstName: firstName, counter: counter)) } case .map(valueType: _): return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSDictionary class]]") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: schema, firstName: firstName, counter: counter)) } case .string(.some(.uri)): return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSString class]] && [NSURL URLWithString:\(rawObjectName)] != nil") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: schema, firstName: firstName, counter: counter)) } case .string(.some(.dateTime)): return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSString class]] && [[NSValueTransformer valueTransformerForName:\(dateValueTransformerKey)] transformedValue:\(rawObjectName)] != nil") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: schema, firstName: firstName, counter: counter)) } case .string(.some), .string(.none), .enumT(.string): return ObjCIR.ifStmt("[\(rawObjectName) isKindOfClass:[NSString class]]") { return transformToADTInit(renderPropertyInit(propertyToAssign, rawObjectName, schema: schema, firstName: firstName, counter: counter)) } case .oneOf(types:_): fatalError("Nested oneOf types are unsupported at this time. Please file an issue if you require this.") } } return schemas.map(loop) default: switch schema.memoryAssignmentType() { case .copy: return ["\(propertyToAssign) = [\(rawObjectName) copy];"] default: return ["\(propertyToAssign) = \(rawObjectName);"] } } } return ObjCIR.method("- (instancetype)initWithModelDictionary:(NS_VALID_UNTIL_END_OF_SCOPE NSDictionary *)modelDictionary") { return [ "NSParameterAssert(modelDictionary);", ObjCIR.ifStmt("!modelDictionary") { ["return self;"] }, self.isBaseClass ? ObjCIR.ifStmt("!(self = [super init])") { ["return self;"] } : "if (!(self = [super initWithModelDictionary:modelDictionary])) { return self; }", -->self.properties.map { (name, prop) in ObjCIR.scope {[ "__unsafe_unretained id value = modelDictionary[\(name.objcLiteral())]; // Collection will retain.", ObjCIR.ifStmt("value != nil") {[ ObjCIR.ifStmt("value != (id)kCFNull") { renderPropertyInit("self->_\(name.snakeCaseToPropertyName())", "value", schema: prop.schema, firstName: name) }, "self->_\(dirtyPropertiesIVarName).\(dirtyPropertyOption(propertyName: name, className: className)) = 1;" ]} ]} }, ObjCIR.ifStmt("[self class] == [\(self.className) class]") { [renderPostInitNotification(type: "PlankModelInitTypeDefault")] }, "return self;" ] } } }
9de7c074f4a77d512f1a8c6802c7202c
57.951049
217
0.513405
false
false
false
false
dmitrinesterenko/Phony
refs/heads/master
Phony/Player.swift
gpl-2.0
1
// // Player.swift // Phony // // Created by Dmitri Nesterenko on 5/3/15. // Copyright (c) 2015 Dmitri Nesterenko. All rights reserved. // import Foundation import AVFoundation class Player{ var audioPlayer = AVAudioPlayer() var currentFileUrl = NSURL() var currentTime : NSTimeInterval{ return audioPlayer.currentTime } var duration : NSTimeInterval{ return audioPlayer.duration } var playing : Bool{ return audioPlayer.playing } init (){ } init(fileURL: NSURL){ var error:NSError? self.currentFileUrl = fileURL audioPlayer = AVAudioPlayer(contentsOfURL: self.currentFileUrl, error: &error) if error != nil{ Log.exception(error!.localizedDescription) } } convenience init(filePath: String){ let fileURL = NSURL(string:filePath) self.init(fileURL: fileURL!) } func play(){ self.audioPlayer.prepareToPlay() self.audioPlayer.play() } }
ef206c8b5fb5a7c5f8dcef14215a7d98
18.618182
86
0.592764
false
false
false
false
adamnemecek/AudioKit
refs/heads/main
Sources/AudioKit/Audio Files/Format Converter/FormatConverter.swift
mit
1
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation /** FormatConverter wraps the more complex AVFoundation and CoreAudio audio conversions in an easy to use format. ```swift let options = FormatConverter.Options() // any options left nil will adopt the value of the input file options.format = "wav" options.sampleRate = 48000 options.bitDepth = 24 let converter = FormatConverter(inputURL: oldURL, outputURL: newURL, options: options) converter.start { error in // the error will be nil on success } ``` */ public class FormatConverter { // MARK: - properties /// The source audio file public var inputURL: URL? /// The audio file to be created after conversion public var outputURL: URL? /// Options for conversion public var options: Options? // MARK: - private properties // The reader needs to exist outside the start func otherwise the async nature of the // AVAssetWriterInput will lose its reference var reader: AVAssetReader? var writer: AVAssetWriter? // MARK: - initialization /// init with input, output and options - then start() public init(inputURL: URL, outputURL: URL, options: Options? = nil) { self.inputURL = inputURL self.outputURL = outputURL self.options = options ?? Options() } deinit { reader = nil writer = nil inputURL = nil outputURL = nil options = nil } // MARK: - functions /// The entry point for file conversion /// - Parameter completionHandler: the callback that will be triggered when process has completed. public func start(completionHandler: FormatConverterCallback? = nil) { guard let inputURL = self.inputURL else { completionHandler?(Self.createError(message: "Input file can't be nil.")) return } guard let outputURL = self.outputURL else { completionHandler?(Self.createError(message: "Output file can't be nil.")) return } let inputFormat = inputURL.pathExtension.lowercased() // verify inputFormat, only allow files with path extensions for speed? guard FormatConverter.inputFormats.contains(inputFormat) else { completionHandler?(Self.createError(message: "The input file format is in an incompatible format: \(inputFormat)")) return } if FileManager.default.fileExists(atPath: outputURL.path) { if options?.eraseFile == true { Log("Warning: removing existing file at", outputURL.path) try? FileManager.default.removeItem(at: outputURL) } else { let message = "The output file exists already. You need to choose a unique URL or delete the file." completionHandler?(Self.createError(message: message)) return } } if options?.format == nil { options?.format = outputURL.pathExtension.lowercased() } // Format checks are necessary as AVAssetReader has opinions about compressed // PCM output, any supported input if Self.isPCM(url: outputURL) == true { // PCM output convertToPCM(completionHandler: completionHandler) // PCM input, compressed output } else if Self.isPCM(url: inputURL) == true, Self.isCompressed(url: outputURL) == true { convertPCMToCompressed(completionHandler: completionHandler) // Compressed input and output, won't do sample rate } else if Self.isCompressed(url: inputURL) == true, Self.isCompressed(url: outputURL) == true { convertCompressed(completionHandler: completionHandler) } else { completionHandler?(Self.createError(message: "Unable to determine formats for conversion")) } } } // MARK: - Definitions extension FormatConverter { /// FormatConverterCallback is the callback format for start() /// - Parameter: error This will contain one parameter of type Error which is nil if the conversion was successful. public typealias FormatConverterCallback = (_ error: Error?) -> Void /// Formats that this class can write public static let outputFormats = ["wav", "aif", "caf", "m4a"] public static let defaultOutputFormat = "wav" /// Formats that this class can read public static let inputFormats = FormatConverter.outputFormats + [ "mp3", "snd", "au", "sd2", "aif", "aiff", "aifc", "aac", "mp4", "m4v", "mov", "ts", "", // allow files with no extension. convertToPCM can still read the type ] /// An option to block upsampling to a higher bit depth than the source. /// For example, converting to 24bit from 16 doesn't have much benefit public enum BitDepthRule { /// Don't allow upsampling to 24bit if the src is 16 case lessThanOrEqual /// allow any conversaion case any } /// The conversion options, leave any property nil to adopt the value of the input file /// bitRate assumes a stereo bit rate and the converter will half it for mono public struct Options { /// Audio Format as a string public var format: String? /// Sample Rate in Hertz public var sampleRate: Double? /// used only with PCM data public var bitDepth: UInt32? /// used only when outputting compressed audio public var bitRate: UInt32 = 128000 { didSet { bitRate = bitRate.clamped(to: 64000 ... 320000) } } /// An option to block upsampling to a higher bit depth than the source. /// default value is `.lessThanOrEqual` public var bitDepthRule: BitDepthRule = .lessThanOrEqual /// How many channels to convert to. Typically 1 or 2 public var channels: UInt32? /// Maps to PCM Convertion format option `AVLinearPCMIsNonInterleaved` public var isInterleaved: Bool? /// Overwrite existing files, set false if you want to handle this before you call start() public var eraseFile: Bool = true public init() {} /// Create options by parsing the contents of the url and using the audio settings /// in the file /// - Parameter url: The audio file to open and parse public init?(url: URL) { guard let avFile = try? AVAudioFile(forReading: url) else { return nil } self.init(audioFile: avFile) } /// Create options by parsing the audioFile for its settings /// - Parameter audioFile: an AVAudioFile to parse public init?(audioFile: AVAudioFile) { let streamDescription = audioFile.fileFormat.streamDescription.pointee format = audioFile.url.pathExtension // FormatConverter.formatIDToString(streamDescription.mFormatID) sampleRate = streamDescription.mSampleRate bitDepth = streamDescription.mBitsPerChannel channels = streamDescription.mChannelsPerFrame } /// Create PCM Options /// - Parameters: /// - pcmFormat: wav, aif, or caf /// - sampleRate: Sample Rate /// - bitDepth: Bit Depth, or bits per channel /// - channels: How many channels public init?(pcmFormat: String, sampleRate: Double? = nil, bitDepth: UInt32? = nil, channels: UInt32? = nil) { format = pcmFormat self.sampleRate = sampleRate self.bitDepth = bitDepth self.channels = channels } } func completionProxy(error: Error?, deleteOutputOnError: Bool = true, completionHandler: FormatConverterCallback? = nil) { guard error != nil, deleteOutputOnError, let outputURL = outputURL, FileManager.default.fileExists(atPath: outputURL.path) else { completionHandler?(error) return } do { Log("Deleting on error", outputURL.path) try FileManager.default.removeItem(at: outputURL) } catch let err as NSError { Log("Failed to remove file", outputURL, err) } completionHandler?(error) } }
3cec6bdb421b0ed700e4bc3874dfce9d
34.957983
127
0.619304
false
false
false
false
alitaso345/swift-annict-client
refs/heads/master
AnnictAPIClient/CreateRecordResponse.swift
mit
1
struct CreateRecordResponse : JSONDecodable { let id: Int let comment: String? let rating: Int? let isModified: Bool let likesCount: Int let commentsCount: Int let createdAt: String let user: User let work: Work let episode: Episode init(json: Any) throws { guard let dictionary = json as? [String : Any] else { throw JSONDecodeError.invalidFormat(json: json) } guard let id = dictionary["id"] as? Int else { throw JSONDecodeError.missingValue( key: "id", actualValue: dictionary["id"]) } if let comment = dictionary["comment"] as? String { self.comment = comment } else { self.comment = nil } if let rating = dictionary["rating"] as? Int { self.rating = rating } else { self.rating = nil } guard let isModified = dictionary["is_modified"] as? Bool else { throw JSONDecodeError.missingValue( key: "is_modified", actualValue: dictionary["is_modified"]) } guard let likesCount = dictionary["likes_count"] as? Int else { throw JSONDecodeError.missingValue( key: "likes_count", actualValue: dictionary["likes_count"]) } guard let commentsCount = dictionary["comments_count"] as? Int else { throw JSONDecodeError.missingValue( key: "comments_count", actualValue: dictionary["comments_count"]) } guard let createdAt = dictionary["created_at"] as? String else { throw JSONDecodeError.missingValue( key: "created_at", actualValue: dictionary["created_at"]) } guard let userObject = dictionary["user"] else { throw JSONDecodeError.missingValue( key: "user", actualValue: dictionary["user"]) } guard let workObject = dictionary["work"] else { throw JSONDecodeError.missingValue( key: "work", actualValue: dictionary["work"]) } if let episodeObject = dictionary["episode"] { var episodeJSON = episodeObject as? [String : Any] episodeJSON?["work"] = workObject self.episode = try Episode(json: episodeJSON as Any) } else { throw JSONDecodeError.missingValue( key: "episode", actualValue: dictionary["episode"]) } self.id = id self.isModified = isModified self.likesCount = likesCount self.commentsCount = commentsCount self.createdAt = createdAt self.user = try User(json: userObject) self.work = try Work(json: workObject) } }
22245c6f4115c5ca8093ad90f8b4f65b
30.659341
77
0.552239
false
false
false
false
Aioria1314/WeiBo
refs/heads/master
WeiBo/WeiBo/Classes/Views/ZXCComposeViewController.swift
mit
1
// // ZXCComposeViewController.swift // WeiBo // // Created by Aioria on 2017/4/5. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit import SVProgressHUD class ZXCComposeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.red setNavUI() setupUI() } // Mark: ------------------------------------------ fileprivate lazy var emoticonKeyBoard: ZXCEmoticonKeyBoard = { let keyboard = ZXCEmoticonKeyBoard() keyboard.size = CGSize(width: ScreenWidth, height: 216) return keyboard }() fileprivate lazy var txtView: ZXCTextView = { let txt = ZXCTextView() txt.placeHolder = "占位文字" txt.alwaysBounceVertical = true txt.font = UIFont.systemFont(ofSize: 16) txt.textColor = UIColor.gray // txt.autocorrectionType = .no return txt }() fileprivate lazy var pictureView: ZXCComposePictuerView = { let pictureView = ZXCComposePictuerView() return pictureView }() fileprivate lazy var toolBar: ZXCComposeToolBar = ZXCComposeToolBar() fileprivate lazy var titleLabel: UILabel = { let lab = UILabel(fontSize: 17, textColor: UIColor.darkGray, text:"") if let name = ZXCUserAccountViewModel.sharedViewModel.userAccount?.name { let message = "发微博\n" + name let range = (message as NSString).range(of: name) let attributedStr = NSMutableAttributedString(string: message) attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.orange], range: range) lab.numberOfLines = 0 lab.textAlignment = .center lab.attributedText = attributedStr } else { lab.text = "发微博" } lab.sizeToFit() return lab }() fileprivate lazy var btnSend: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal) btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted) btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled) btn.addTarget(self, action: #selector(sendAction), for: .touchUpInside) btn.setTitle("发送", for: .normal) btn.setTitleColor(UIColor.white, for: .normal) btn.setTitleColor(UIColor.darkGray, for: .disabled) btn.size = CGSize(width: 50, height: 40) return btn }() fileprivate func setNavUI() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction)) navigationItem.titleView = titleLabel navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btnSend) navigationItem.rightBarButtonItem?.isEnabled = false } fileprivate func setupUI() { NotificationCenter.default.addObserver(self, selector: #selector(didSelectedDeleteButtonAction (no:)), name:NSNotification.Name(rawValue: DidSelectedDeleteButtonNoti) , object: nil) NotificationCenter.default.addObserver(self, selector: #selector(notiAction (no:)), name:NSNotification.Name(rawValue: DidSelectedemoticonButtonNoti) , object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardFranmeChangeAction(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) view.addSubview(toolBar) view.addSubview(txtView) view.addSubview(pictureView) pictureView.addPictureClosure = {[weak self] in self?.didselectedPicture() } toolBar.buttonClickClosuer = {[weak self] (type: ZXCToolBarButtonType)->() in switch type { case .picture: self?.didselectedPicture() case .mention: print("1") case .trend: print("2") case .emoticon: self?.didSelectedEmotion() case .add: print("4") } } // txtView.becomeFirstResponder() txtView.keyboardDismissMode = .onDrag txtView.delegate = self toolBar.snp.makeConstraints { (make) in make.left.bottom.right.equalTo(view) make.height.equalTo(35) } txtView.snp.makeConstraints { (make) in make.top.equalTo(self.topLayoutGuide.snp.bottom).offset(5) make.left.equalTo(view).offset(5) make.right.equalTo(view).offset(-5) make.bottom.equalTo(toolBar.snp.top).offset(-5) } pictureView.snp.makeConstraints { (make) in make.top.equalTo(txtView).offset(100) make.centerX.equalTo(self.view) make.width.height.equalTo(ScreenWidth - MarginHome * 2) } } @objc private func keyboardFranmeChangeAction(noti: Notification) { let userInfo = noti.userInfo! let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect // let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double toolBar.snp.updateConstraints { (make) in make.bottom.equalTo(self.view).offset(-ScreenHeight + keyboardFrame.origin.y) } UIView.animate(withDuration: 1) { self.view.layoutIfNeeded() } } @objc fileprivate func cancelAction() { self.view.endEditing(true) dismiss(animated: true, completion: nil) } @objc fileprivate func didSelectedDeleteButtonAction (no: Notification) { txtView.deleteBackward() } @objc fileprivate func sendAction() { SVProgressHUD.show() let accessToken = ZXCUserAccountViewModel.sharedViewModel.accessToken! let status = txtView.emoticonText // var sendMessage = "" // // txtView.attributedText.enumerateAttributes(in: NSMakeRange(0, txtView.attributedText.length), options: []) { (info, range, _) in // // print(info, NSStringFromRange(range)) // // // if let attachment = info["NSAttachment"] as? ZXCTextAttachment // { // // let emoticonModel = attachment.emoticonModel! // // let chs = emoticonModel.chs! // // sendMessage += chs // // } // else // { // let subAttributedStr = txtView.attributedText.attributedSubstring(from: range) // // let text = subAttributedStr.string // sendMessage += text // } // } if pictureView.images.count > 0 { let image = pictureView.images.first ZXCNetworkTools.sharedTools.sendWeiBoMessage(accessToken: accessToken, status: status, pic: image!, finishCallBack: { (response, error) in SVProgressHUD.dismiss() if (error != nil) { SVProgressHUD.showError(withStatus: "发送失败") } else { SVProgressHUD.showSuccess(withStatus: "发送成功") } }) } else { ZXCNetworkTools.sharedTools.sendWeiBoMessage(accessToken: accessToken, status: status) { (response, error) in SVProgressHUD.dismiss() if (error != nil) { SVProgressHUD.showError(withStatus: "发送失败") } else { SVProgressHUD.showSuccess(withStatus: "发送成功") } } } // dismiss(animated: true, completion: nil) } @objc fileprivate func notiAction (no: Notification) { let obj = no.object as! ZXCEmoticonModel txtView.insertEmoticon(emoticonModel: obj) ZXCEmoticonTools.sharedTools.saveRecentEmoticonArray(emoticon: obj) emoticonKeyBoard.reloadRecentData() // if obj.type == "0" { // // let lastAttributedStr = NSMutableAttributedString(attributedString: txtView.attributedText) // // // let image = UIImage(named: obj.path!) // // let attachMent = NSTextAttachment() // // attachMent.image = image // // let linHeight = txtView.font!.lineHeight // // attachMent.bounds = CGRect(x: 0, y: -4, width: linHeight, height: linHeight) // // let attributedStr = NSAttributedString(attachment: attachMent) // // var selectedRange = txtView.selectedRange // // lastAttributedStr.replaceCharacters(in: selectedRange, with: attributedStr) //// lastAttributedStr.append(attributedStr) // // lastAttributedStr.addAttributes([NSFontAttributeName: txtView.font!], range: NSMakeRange(0, lastAttributedStr.length)) // // txtView.attributedText = lastAttributedStr // // selectedRange.location += 1 // // txtView.selectedRange = selectedRange // // txtView.delegate?.textViewDidChange?(txtView) // // NotificationCenter.default.post(name: Notification.Name.UITextViewTextDidChange, object: nil) // // } else { // // let emoji = (obj.code! as NSString).emoji()! // txtView.insertText(emoji) // // } } deinit { NotificationCenter.default.removeObserver(self) } } extension ZXCComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { fileprivate func didselectedPicture () { let imgPicCtrler = UIImagePickerController() imgPicCtrler.delegate = self if UIImagePickerController.isSourceTypeAvailable(.camera) { imgPicCtrler.sourceType = .camera } else { imgPicCtrler.sourceType = .photoLibrary } // //判断摄像头是否可用 // if UIImagePickerController.isCameraDeviceAvailable(.front) // { // //前置摄像头 // } // if UIImagePickerController.isCameraDeviceAvailable(.rear) // { // //后置摄像头 // } // //开启编辑模式 // imgPicCtrler.allowsEditing = true self.present(imgPicCtrler, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage let currentImage = scaleImage(scaleWidth: 200, image: image) self.pictureView.addImage(image: currentImage) picker.dismiss(animated: true, completion: nil) } fileprivate func scaleImage(scaleWidth: CGFloat, image: UIImage) -> UIImage { let scaleHeight = image.size.height * scaleWidth / image.size.width let scaleSize = CGSize(width: scaleWidth, height: scaleHeight) UIGraphicsBeginImageContext(scaleSize) image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize)) let currentImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return currentImage! } } extension ZXCComposeViewController { fileprivate func didSelectedEmotion() { // txtView.inputAccessoryView if txtView.inputView == nil { txtView.inputView = emoticonKeyBoard toolBar.switchEmoticon(isEmoticon: true) } else { txtView.inputView = nil toolBar.switchEmoticon(isEmoticon: false) } txtView.becomeFirstResponder() txtView.reloadInputViews() } } extension ZXCComposeViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { navigationItem.rightBarButtonItem?.isEnabled = textView.hasText } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.view.endEditing(true) } }
b6776f2bc99a1c77531975799dbe3ff9
29.033557
189
0.552402
false
false
false
false
abertelrud/swift-package-manager
refs/heads/main
Sources/PackageFingerprint/PackageFingerprintStorage.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import Dispatch import PackageModel public protocol PackageFingerprintStorage { func get(package: PackageIdentity, version: Version, observabilityScope: ObservabilityScope, callbackQueue: DispatchQueue, callback: @escaping (Result<[Fingerprint.Kind: Fingerprint], Error>) -> Void) func put(package: PackageIdentity, version: Version, fingerprint: Fingerprint, observabilityScope: ObservabilityScope, callbackQueue: DispatchQueue, callback: @escaping (Result<Void, Error>) -> Void) func get(package: PackageReference, version: Version, observabilityScope: ObservabilityScope, callbackQueue: DispatchQueue, callback: @escaping (Result<[Fingerprint.Kind: Fingerprint], Error>) -> Void) func put(package: PackageReference, version: Version, fingerprint: Fingerprint, observabilityScope: ObservabilityScope, callbackQueue: DispatchQueue, callback: @escaping (Result<Void, Error>) -> Void) } public extension PackageFingerprintStorage { func get(package: PackageIdentity, version: Version, kind: Fingerprint.Kind, observabilityScope: ObservabilityScope, callbackQueue: DispatchQueue, callback: @escaping (Result<Fingerprint, Error>) -> Void) { self.get(package: package, version: version, observabilityScope: observabilityScope, callbackQueue: callbackQueue) { result in self.get(kind: kind, result, callback: callback) } } func get(package: PackageReference, version: Version, kind: Fingerprint.Kind, observabilityScope: ObservabilityScope, callbackQueue: DispatchQueue, callback: @escaping (Result<Fingerprint, Error>) -> Void) { self.get(package: package, version: version, observabilityScope: observabilityScope, callbackQueue: callbackQueue) { result in self.get(kind: kind, result, callback: callback) } } private func get(kind: Fingerprint.Kind, _ fingerprintsResult: Result<[Fingerprint.Kind: Fingerprint], Error>, callback: @escaping (Result<Fingerprint, Error>) -> Void) { callback(fingerprintsResult.tryMap { fingerprints in guard let fingerprint = fingerprints[kind] else { throw PackageFingerprintStorageError.notFound } return fingerprint }) } } public enum PackageFingerprintStorageError: Error, Equatable, CustomStringConvertible { case conflict(given: Fingerprint, existing: Fingerprint) case notFound public var description: String { switch self { case .conflict(let given, let existing): return "Fingerprint \(given) is different from previously recorded value \(existing)" case .notFound: return "Not found" } } }
20f97200a85dd066fcdc90be1a1f1c73
38.184783
134
0.616644
false
false
false
false
avito-tech/Marshroute
refs/heads/master
Marshroute/Sources/Transitions/TransitionAnimations/ModalMasterDetail/ModalMasterDetailTransitionsAnimator.swift
mit
1
import UIKit /// Аниматор, выполняющий модальный переход на UISplitViewController. /// Также выполняет обратный переход open class ModalMasterDetailTransitionsAnimator: TransitionsAnimator { open var shouldAnimate = true open var targetModalTransitionStyle: UIModalTransitionStyle open var targetModalPresentationStyle: UIModalPresentationStyle // MARK: - Init public init( targetModalTransitionStyle: UIModalTransitionStyle?, targetModalPresentationStyle: UIModalPresentationStyle?) { self.targetModalTransitionStyle = targetModalTransitionStyle ?? .coverVertical self.targetModalPresentationStyle = targetModalPresentationStyle ?? .fullScreen } public init() { self.targetModalTransitionStyle = .coverVertical self.targetModalPresentationStyle = .fullScreen } // MARK: - TransitionsAnimator open func animatePerformingTransition(animationContext context: ModalMasterDetailPresentationAnimationContext) { context.targetViewController.modalTransitionStyle = targetModalTransitionStyle context.targetViewController.modalPresentationStyle = targetModalPresentationStyle context.sourceViewController.present( context.targetViewController, animated: shouldAnimate, completion: nil ) shouldAnimate = true } open func animateUndoingTransition(animationContext context: ModalMasterDetailDismissalAnimationContext) { context.targetViewController.dismiss( animated: shouldAnimate, completion: nil ) shouldAnimate = true } }
959c96c4434ee0fd2cd51f5347e6b541
33.489796
114
0.723077
false
false
false
false
bitjammer/swift
refs/heads/master
test/expr/unary/selector/selector.swift
apache-2.0
3
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -disable-objc-attr-requires-foundation-module -typecheck %s -verify import ObjectiveC // REQUIRES: objc_interop @objc class A { } @objc class B { } class C1 { @objc init(a: A, b: B) { } @objc func method1(_ a: A, b: B) { } @objc(someMethodWithA:B:) func method2(_ a: A, b: B) { } @objc class func method3(_ a: A, b: B) { } // expected-note{{found this candidate}} @objc class func method3(a: A, b: B) { } // expected-note{{found this candidate}} @objc(ambiguous1:b:) class func ambiguous(a: A, b: A) { } // expected-note{{found this candidate}} @objc(ambiguous2:b:) class func ambiguous(a: A, b: B) { } // expected-note{{found this candidate}} @objc func getC1() -> AnyObject { return self } @objc func testUnqualifiedSelector(_ a: A, b: B) { _ = #selector(testUnqualifiedSelector(_:b:)) let testUnqualifiedSelector = 1 _ = #selector(testUnqualifiedSelector(_:b:)) _ = testUnqualifiedSelector // suppress unused warning } @objc func testParam(_ testParam: A) { // expected-note{{'testParam' declared here}} _ = #selector(testParam) // expected-error{{argument of '#selector' cannot refer to parameter 'testParam'}} } @objc func testVariable() { let testVariable = 1 // expected-note{{'testVariable' declared here}} _ = #selector(testVariable) // expected-error{{argument of '#selector' cannot refer to variable 'testVariable'}} } } @objc protocol P1 { func method4(_ a: A, b: B) static func method5(_ a: B, b: B) } extension C1 { final func method6() { } // expected-note{{add '@objc' to expose this instance method to Objective-C}}{{3-3=@objc }} } func testSelector(_ c1: C1, p1: P1, obj: AnyObject) { // Instance methods on an instance let sel1 = #selector(c1.method1) _ = #selector(c1.method1(_:b:)) _ = #selector(c1.method2) // Instance methods on a class. _ = #selector(C1.method1) _ = #selector(C1.method1(_:b:)) _ = #selector(C1.method2) // Class methods on a class. _ = #selector(C1.method3(_:b:)) _ = #selector(C1.method3(a:b:)) // Methods on a protocol. _ = #selector(P1.method4) _ = #selector(P1.method4(_:b:)) _ = #selector(P1.method5) // expected-error{{static member 'method5' cannot be used on protocol metatype 'P1.Protocol'}} _ = #selector(P1.method5(_:b:)) // expected-error{{static member 'method5(_:b:)' cannot be used on protocol metatype 'P1.Protocol'}} _ = #selector(p1.method4) _ = #selector(p1.method4(_:b:)) _ = #selector(type(of: p1).method5) _ = #selector(type(of: p1).method5(_:b:)) // Interesting expressions that refer to methods. _ = #selector(Swift.AnyObject.method1) _ = #selector(AnyObject.method1!) _ = #selector(obj.getC1?().method1) // Initializers _ = #selector(C1.init(a:b:)) // Make sure the result has type "ObjectiveC.Selector" let sel2: Selector sel2 = sel1 _ = sel2 let dict: [Selector: Int] = [:] let _: Int? = dict[#selector(c1.method1)] } func testAmbiguity() { _ = #selector(C1.method3) // expected-error{{ambiguous use of 'method3'}} _ = #selector(C1.ambiguous) // expected-error{{ambiguous use of 'ambiguous(a:b:)'}} } func testUnusedSelector() { #selector(C1.getC1) // expected-warning{{result of '#selector' is unused}} } func testNonObjC(_ c1: C1) { _ = #selector(c1.method6) // expected-error{{argument of '#selector' refers to instance method 'method6()' that is not exposed to Objective-C}} } func testParseErrors1() { _ = #selector foo // expected-error{{expected '(' following '#selector'}} } func testParseErrors2() { _ = #selector( // expected-error{{expected expression naming a method within '#selector(...)'}} } func testParseErrors3(_ c1: C1) { _ = #selector( // expected-note{{to match this opening '('}} c1.method1(_:b:) // expected-error{{expected ')' to complete '#selector' expression}} } func testParseErrors4() { // Subscripts _ = #selector(C1.subscript) // expected-error{{type 'C1.Type' has no subscript members}} } // SR-1827 let optionalSel: Selector? = nil switch optionalSel { case #selector(C1.method1)?: break } @objc class SR1827 { func bar() {} } switch optionalSel { case #selector(SR1827.bar): // expected-error{{expression pattern of type 'Selector' cannot match values of type 'Selector?'}} {{26-26=?}} break case #selector(SR1827.bar)!: // expected-error{{cannot force unwrap value of non-optional type 'Selector'}} break case #selector(SR1827.bar)?: break default: break }
db22dca6c42c6e32b9be04074bc68542
30.381944
145
0.657225
false
true
false
false
Rahulclaritaz/rahul
refs/heads/master
ixprez/ixprez/XPContactHeaderTableViewCell.swift
mit
1
// // XPContactHeaderTableViewCell.swift // ixprez // // Created by Claritaz Techlabs on 14/06/17. // Copyright © 2017 Claritaz Techlabs. All rights reserved. // import UIKit class XPContactHeaderTableViewCell: UITableViewCell { @IBOutlet weak var xprezButton = UIButton () @IBOutlet weak var xprezBottomLine = UIView () @IBOutlet weak var recentButton = UIButton () @IBOutlet weak var recentBottomLine = UIView () @IBOutlet weak var searchBar = UISearchBar () override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
8e7d0765a90dfce9730ec2388f152ccb
25
65
0.685897
false
false
false
false
Daniel-Lopez/EZSwiftExtensions
refs/heads/master
ScaledPageView/Pods/EZSwiftExtensions/Sources/UIColorExtensions.swift
mit
3
// // UIColorExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension UIColor { /// EZSE: init method with RGB values from 0 to 255, instead of 0 to 1. With alpha(default:1) public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a) } /// EZSE: init method with hex string and alpha(default: 1) public convenience init?(hexString: String, alpha: CGFloat = 1.0) { var formatted = hexString.stringByReplacingOccurrencesOfString("0x", withString: "") formatted = formatted.stringByReplacingOccurrencesOfString("#", withString: "") if let hex = Int(formatted, radix: 16) { let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0) let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0) let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0) self.init(red: red, green: green, blue: blue, alpha: alpha) } else { return nil } } /// EZSE: init method from Gray value and alpha(default:1) public convenience init(gray: CGFloat, alpha: CGFloat = 1) { self.init(red: gray/255, green: gray/255, blue: gray/255, alpha: alpha) } /// EZSE: Red component of UIColor (get-only) public var redComponent: Int { var r: CGFloat = 0 getRed(&r, green: nil, blue: nil, alpha: nil) return Int(r * 255) } /// EZSE: Green component of UIColor (get-only) public var greenComponent: Int { var g: CGFloat = 0 getRed(nil, green: &g, blue: nil, alpha: nil) return Int(g * 255) } /// EZSE: blue component of UIColor (get-only) public var blueComponent: Int { var b: CGFloat = 0 getRed(nil, green: nil, blue: &b, alpha: nil) return Int(b * 255) } /// EZSE: Alpha of UIColor (get-only) public var alpha: Int { var a: CGFloat = 0 getRed(nil, green: nil, blue: nil, alpha: &a) return Int(a) } /// EZSE: Returns random UIColor with random alpha(default: false) public static func randomColor(randomAlpha: Bool = false) -> UIColor { let randomRed = CGFloat.random() let randomGreen = CGFloat.random() let randomBlue = CGFloat.random() let alpha = randomAlpha ? CGFloat.random() : 1.0 return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: alpha) } } private extension CGFloat { /// SwiftRandom extension static func random(lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat { return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (upper - lower) + lower } }
b8645a336cf85586252a023da9a7dcbb
34.734177
97
0.610344
false
false
false
false
Authman2/Pix
refs/heads/master
Pods/Eureka/Source/Core/Row.swift
apache-2.0
4
// Row.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class RowOf<T: Equatable>: BaseRow { private var _value: T? { didSet { guard _value != oldValue else { return } guard let form = section?.form else { return } if let delegate = form.delegate { delegate.valueHasBeenChanged(for: self, oldValue: oldValue, newValue: value) callbackOnChange?() } guard let t = tag else { return } form.tagToValues[t] = (value != nil ? value! : NSNull()) if let rowObservers = form.rowObservers[t]?[.hidden]{ for rowObserver in rowObservers { (rowObserver as? Hidable)?.evaluateHidden() } } if let rowObservers = form.rowObservers[t]?[.disabled]{ for rowObserver in rowObservers { (rowObserver as? Disableable)?.evaluateDisabled() } } } } /// The typed value of this row. open var value : T?{ set (newValue){ _value = newValue guard let _ = section?.form else { return } wasChanged = true if validationOptions.contains(.validatesOnChange) || (wasBlurred && validationOptions.contains(.validatesOnChangeAfterBlurred)) || !isValid { validate() updateCell() } } get { return _value } } /// The untyped value of this row. public override var baseValue: Any? { get { return value } set { value = newValue as? T } } /// Variable used in rows with options that serves to generate the options for that row. public var dataProvider: DataProvider<T>? /// Block variable used to get the String that should be displayed for the value of this row. public var displayValueFor : ((T?) -> String?)? = { return $0.map { String(describing: $0) } } public required init(tag: String?){ super.init(tag: tag) } internal var rules: [ValidationRuleHelper<T>] = [] @discardableResult public override func validate() -> [ValidationError] { validationErrors = rules.flatMap { $0.validateFn(value) } return validationErrors } public func add<Rule: RuleType>(rule: Rule) where T == Rule.RowValueType{ let validFn: ((T?) -> ValidationError?) = { (val: T?) in return rule.isValid(value: val) } rules.append(ValidationRuleHelper(validateFn: validFn, rule: rule)) } public func add(ruleSet: RuleSet<T>){ rules.append(contentsOf: ruleSet.rules) } public func remove(ruleWithIdentifier identifier: String) { if let index = rules.index(where: { (validationRuleHelper) -> Bool in return validationRuleHelper.rule.id == identifier }){ rules.remove(at: index) } } public func removeAllRules() { validationErrors.removeAll() rules.removeAll() } } /// Generic class that represents an Eureka row. open class Row<Cell: CellType>: RowOf<Cell.Value>, TypedRowType where Cell: BaseCell { /// Responsible for creating the cell for this row. public var cellProvider = CellProvider<Cell>() /// The type of the cell associated to this row. public let cellType: Cell.Type! = Cell.self private var _cell: Cell! { didSet { RowDefaults.cellSetup["\(type(of: self))"]?(_cell, self) (callbackCellSetup as? ((Cell) -> ()))?(_cell) } } /// The cell associated to this row. public var cell : Cell! { return _cell ?? { let result = cellProvider.makeCell(style: self.cellStyle) result.row = self result.setup() _cell = result return _cell }() } /// The untyped cell associated to this row public override var baseCell: BaseCell { return cell } public required init(tag: String?) { super.init(tag: tag) } /** Method that reloads the cell */ override open func updateCell() { super.updateCell() cell.update() customUpdateCell() RowDefaults.cellUpdate["\(type(of: self))"]?(cell, self) callbackCellUpdate?() } /** Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell. */ open override func didSelect() { super.didSelect() if !isDisabled { cell?.didSelect() } customDidSelect() callbackCellOnSelection?() } /** Will be called inside `didSelect` method of the row. Can be used to customize row selection from the definition of the row. */ open func customDidSelect(){} /** Will be called inside `updateCell` method of the row. Can be used to customize reloading a row from its definition. */ open func customUpdateCell(){} }
0e39e710a4c65d88c353286b10829d91
32.101064
155
0.612566
false
false
false
false
devincoughlin/swift
refs/heads/master
test/Constraints/function_conversion.swift
apache-2.0
8
// RUN: %target-typecheck-verify-swift -swift-version 4 // rdar://problem/31969605 class Base {} class Derived : Base {} protocol Refined {} protocol Proto : Refined {} extension Base : Refined {} func baseFn(_: Base) {} func superclassConversion(fn: @escaping (Base) -> ()) { let _: (Derived) -> () = fn } func existentialConversion(fn: @escaping (Refined) -> ()) { let _: (Proto) -> () = fn let _: (Base) -> () = fn let _: (Derived) -> () = fn } // rdar://problem/31725325 func a<b>(_: [(String, (b) -> () -> Void)]) {} func a<b>(_: [(String, (b) -> () throws -> Void)]) {} class c { func e() {} static var d = [("", e)] } a(c.d) func b<T>(_: (T) -> () -> ()) {} b(c.e) func bar(_: () -> ()) {} func bar(_: () throws -> ()) {} func bar_empty() {} bar(bar_empty) func consumeNoEscape(_ f: (Int) -> Int) {} func consumeEscaping(_ f: @escaping (Int) -> Int) {} func takesAny(_ f: Any) {} func twoFns(_ f: (Int) -> Int, _ g: @escaping (Int) -> Int) { // expected-note@-1 {{parameter 'f' is implicitly non-escaping}} takesAny(f) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} takesAny(g) var h = g h = f // expected-error {{assigning non-escaping parameter 'f' to an @escaping closure}} } takesAny(consumeNoEscape) takesAny(consumeEscaping) var noEscapeParam: ((Int) -> Int) -> () = consumeNoEscape var escapingParam: (@escaping (Int) -> Int) -> () = consumeEscaping noEscapeParam = escapingParam // expected-error {{converting non-escaping value to '(Int) -> Int' may allow it to escape}} escapingParam = takesAny noEscapeParam = takesAny // expected-error {{converting non-escaping value to 'Any' may allow it to escape}}
fc680fb2d4bf28dbd5cf03100aa8e2dc
25.138462
122
0.612713
false
false
false
false
halawata13/Golf
refs/heads/master
Golf/model/Card.swift
mit
1
import Foundation class Card { let suit: PlayingCard.Suit let number: UInt var column: Int? var row: Int? var imageName: String { return suit.rawValue + String(number) } init?(suit: PlayingCard.Suit, number: UInt?) { switch suit { case .spade: fallthrough case .club: fallthrough case .heart: fallthrough case .diamond: guard let number = number else { return nil } if number == 0 || number > 13 { return nil } self.suit = suit self.number = number case .joker: self.suit = .joker self.number = 0 } } }
0a7343b0fc18291c9900af84ffacc2c3
18.74359
50
0.47013
false
false
false
false
spacedrabbit/100-days
refs/heads/master
One00Days/One00Days/IntroSpriteKit/IntroSpriteKit/StarNode.swift
mit
1
// // StarNode.swift // IntroSpriteKit // // Created by Louis Tur on 3/2/16. // Copyright © 2016 SRLabs. All rights reserved. // https://spin.atomicobject.com/2014/12/29/spritekit-physics-tutorial-swift/ import Foundation import UIKit import SpriteKit class StarNode: SKSpriteNode { class func star(location: CGPoint) -> StarNode { let starSprite: StarNode = StarNode(imageNamed: "star.png") starSprite.xScale = 0.075 starSprite.yScale = 0.075 starSprite.position = location starSprite.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "star.png"), size: starSprite.size) if let physics = starSprite.physicsBody { physics.affectedByGravity = true physics.allowsRotation = true physics.dynamic = true physics.linearDamping = 0.75 physics.angularDamping = 0.75 physics.restitution = 0.5 } return starSprite } }
69c812bef7f3b3663ec5ea988e258b28
27.25
109
0.702104
false
false
false
false